예제 #1
0
static int websock_server_data(struct mg_connection *conn,
                               int bits,
                               char *data,
                               size_t data_len,
                               void *udata)
{
	(void)bits;

	ck_assert_ptr_eq((void *)udata, (void *)7531);
	printf("Server: Got %u bytes from the client\n", (unsigned)data_len);

	if (data_len < 3 || 0 != memcmp(data, "bye", 3)) {
		/* Send websocket acknowledge message */
		mg_lock_connection(conn);
		mg_websocket_write(conn,
		                   WEBSOCKET_OPCODE_TEXT,
		                   websocket_acknowledge_msg,
		                   websocket_acknowledge_msg_len);
		mg_unlock_connection(conn);
	} else {
		/* Send websocket acknowledge message */
		mg_lock_connection(conn);
		mg_websocket_write(conn,
		                   WEBSOCKET_OPCODE_TEXT,
		                   websocket_goodbye_msg,
		                   websocket_goodbye_msg_len);
		mg_unlock_connection(conn);
	}

	return 1; /* return 1 to keep the connetion open */
}
예제 #2
0
static int
websock_server_data(struct mg_connection *conn,
                    int bits,
                    char *data,
                    size_t data_len,
                    void *udata)
{
	(void)bits;

	ck_assert_ptr_eq((void *)udata, (void *)7531);
	printf("Server: Got %u bytes from the client\n", (unsigned)data_len);

	if (data_len == 3 && !memcmp(data, "bye", 3)) {
		/* Send websocket goodbye message */
		mg_lock_connection(conn);
		mg_websocket_write(conn,
		                   WEBSOCKET_OPCODE_TEXT,
		                   websocket_goodbye_msg,
		                   websocket_goodbye_msg_len);
		mg_unlock_connection(conn);
	} else if (data_len == 5 && !memcmp(data, "data1", 5)) {
		mg_lock_connection(conn);
		mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok1", 3);
		mg_unlock_connection(conn);
	} else if (data_len == 5 && !memcmp(data, "data2", 5)) {
		mg_lock_connection(conn);
		mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok 2", 4);
		mg_unlock_connection(conn);
	} else if (data_len == 5 && !memcmp(data, "data3", 5)) {
		mg_lock_connection(conn);
		mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, "ok - 3", 6);
		mg_unlock_connection(conn);
	} else {

#if defined(__MINGW32__) || defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunreachable-code"
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#endif

		ck_abort_msg("Got unexpected message from websocket client");


		return 0;

#ifdef __clang__
#pragma clang diagnostic pop
#endif
#if defined(__MINGW32__) || defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
	}

	return 1; /* return 1 to keep the connetion open */
}
예제 #3
0
// Arguments:
//   flags: first byte of websocket frame, see websocket RFC,
//          http://tools.ietf.org/html/rfc6455, section 5.2
//   data, data_len: payload data. Mask, if any, is already applied.
int UIHelper::websocket_data_handler(mg_connection *conn, int flags,
                                  char *data, size_t data_len) {
  (void) flags; // Unused
  
  // Returning zero means stoping websocket conversation.
  // Close the conversation if client has sent us "exit" string.
  if (memcmp(data, "exit", 4) == 0)
    return 0;

  if (strcmp(mg_get_request_info(conn)->uri,"/searchdbquery") == 0)
  {
	  string message(data,data_len);
	  string query;

	  Json::Value jValue;
	  Json::Reader JReader;

    printf("Message: %s\n",message.c_str() );

	  if( JReader.parse(message, jValue) ){
		  try{
			  query = jValue.get("query","").asString();
		  }
		  catch (exception &e){
			  cout << "Exception!:" << e.what() << endl;
		  }
	  }
	  else {
		  printf("Parse error :%s\n",JReader.getFormatedErrorMessages().c_str());
	  }

	  if (query.length()){
		  Json::Value result;
		  instance->dbconnector->query(&query, &result);

		  Json::StyledWriter writer;
		  string result_str = writer.write(result);
		  mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, result_str.c_str(), result_str.length()+1);
	  }

  }
  else
  {
	  //TODO: Echo temporarily
	  mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data, data_len);
  }

  printf("data returned for %s \n",mg_get_request_info(conn)->uri);
  return 1;
}
예제 #4
0
void *ws_server_thread(void *parm)
{
  wsserver::ws_connection* ws_conn = static_cast<wsserver::ws_connection*>(parm);
  mg_connection *conn = ws_conn->conn;
  wsserver* object = static_cast<wsserver*>(mg_get_request_info(conn)->user_data);

  int timer = 0;
  
  if(object->getDebug()) post("ws_server_thread %d\n", ws_conn->index);
  
  /* While the connection is open, send periodic updates */
  while(!ws_conn->closing) {
    usleep(object->mClientUpdateRateMs * 1000);
    timer++;

    WDL_MutexLock(&ws_conn->mutex);

    if (ws_conn->update && ws_conn->newdatafromserver) 
    {
      if (!ws_conn->closing) 
      {        
        if (ws_conn->fromserver.GetLength())
          mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, ws_conn->fromserver.Get(), ws_conn->fromserver.GetLength());
        
        ws_conn->newdatafromserver = false;
      }
    }
    
    /* Send periodic PING to assure websocket remains connected, except if we are closing */
    if (timer%100 == 0 && !ws_conn->closing)
      mg_websocket_write(conn, WEBSOCKET_OPCODE_PING, NULL, 0);
  }
  
  if(object->getDebug()) post("ws_server_thread %d exiting\n", ws_conn->index);
  
  WDL_MutexLock(&ws_conn->mutex);

  // reset connection information to allow reuse by new client
  ws_conn->update = 0;
  ws_conn->index = -1;
  ws_conn->newdatafromserver = false;
  ws_conn->newdatatoserver = true;
  ws_conn->fromserver.Set("");
  if(ws_conn->toserver.Get()) ws_conn->toserver.SetFormatted(MAX_STRING, "dx");
  ws_conn->conn = NULL;
  ws_conn->closing = 2;
  return NULL;
}
예제 #5
0
void processCmd(mg_connection* conn, char* cmd, size_t cmdLen)
{
   // Null-terminate the command and add END_OF_BUF_CHAR to the end of
   // the cmd buffer.  This makes it easier to parse the command
   // token-by-token.
   cmd[cmdLen] = '\0';
   cmd[cmdLen+1] = END_OF_BUF_CHAR;

   char* cmdName = firstToken(cmd);

   if (strcmp("ping", cmdName) == 0) {
      char response[] = "OK";
      mg_websocket_write(conn, 1, response, sizeof(response)-1);
   }
   else if (strcmp("keydownup", cmdName) == 0) {
      char* keyName = nextToken(cmd);
      keypress::keyDownUp(keyName);
   }
   else if (strcmp("keyseq", cmdName) == 0) {
      char* keyName = nextToken(cmd);
      keypress::keySequence(keyName);
   }
   else if (strcmp("keydown", cmdName) == 0) {
      char* keyName = nextToken(cmd);
      keypress::keyDown(keyName);    
   }
   else if (strcmp("keyup", cmdName) == 0) {
      char* keyName = nextToken(cmd);
      keypress::keyUp(keyName);
   }
   else {
      printf("Unhandled cmd \"%s\"\n", cmdName);
   }
}
예제 #6
0
static void iterate_callback(struct mg_connection *c, void *param) {
  if (c->is_websocket) {
    char buf[20];
    int len = snprintf(buf, sizeof(buf), "%d", * (int *) param);
    mg_websocket_write(c, 1, buf, len);
  }
}
예제 #7
0
// sent direct to mg_connection
void send_meta_mc(struct mg_connection *mc, u1_t cmd, u4_t p1, u4_t p2)
{
	meta_t meta;
	meta_set(&meta, cmd, p1, p2);
	
	mg_websocket_write(mc, WS_OPCODE_BINARY, (char*) &meta, 4+2+8);
}
예제 #8
0
파일: websocket.c 프로젝트: Adam23/mongoose
static int iterate_callback(struct mg_connection *c) {
  if (c->is_websocket) {
    char buf[20];
    int len = snprintf(buf, sizeof(buf), "%d", * (int *) c->callback_param);
    mg_websocket_write(c, 1, buf, len);
  }
  return MG_REQUEST_PROCESSED;
}
예제 #9
0
파일: mpd_client.c 프로젝트: rain0r/ympd
static int mpd_notify_callback(struct mg_connection *c, enum mg_event ev) {
    size_t n;

    if(!c->is_websocket)
        return MG_TRUE;

    if(c->callback_param)
    {
        /* error message? */
        n = snprintf(mpd.buf, MAX_SIZE, "{\"type\":\"error\",\"data\":\"%s\"}", 
            (const char *)c->callback_param);

        mg_websocket_write(c, 1, mpd.buf, n);
        return MG_TRUE;
    }

    if(!c->connection_param)
        c->connection_param = calloc(1, sizeof(struct t_mpd_client_session));

    struct t_mpd_client_session *s = (struct t_mpd_client_session *)c->connection_param;

    if(mpd.conn_state != MPD_CONNECTED) {
        n = snprintf(mpd.buf, MAX_SIZE, "{\"type\":\"disconnected\"}");
        mg_websocket_write(c, 1, mpd.buf, n);
    }
    else
    {
        mg_websocket_write(c, 1, mpd.buf, mpd.buf_size);

        if(s->song_id != mpd.song_id)
        {
            n = mpd_put_current_song(mpd.buf);
            mg_websocket_write(c, 1, mpd.buf, n);
            s->song_id = mpd.song_id;
        }

        if(s->queue_version != mpd.queue_version)
        {
            n = snprintf(mpd.buf, MAX_SIZE, "{\"type\":\"update_queue\"}");
            mg_websocket_write(c, 1, mpd.buf, n);
            s->queue_version = mpd.queue_version;
        }
    }

    return MG_TRUE;
}
예제 #10
0
void web_engine::push_message(const char *message)
{
	for (simple_list_wrapper<mg_connection> *curitem = m_websockets.first(); curitem != NULL; curitem = curitem->next())
	{
		int status = mg_websocket_write(curitem->object(), WEBSOCKET_OPCODE_TEXT, message, strlen(message));
		if (status==0) m_websockets.detach(*curitem); // remove inactive clients
	}
}
예제 #11
0
파일: App.cpp 프로젝트: jackpoz/G3D-backup
static void websocket_ready_handler(struct mg_connection* conn) {
    clientSetMutex.lock();
    clientSet.insert(conn);
    clientSetMutex.unlock();

    mg_websocket_write(conn, 0x1, "{\"type\": 0, \"value\":\"server ready\"}");
    debugPrintf("Connection 0x%x: Opened for websocket\n",  (unsigned int)(uintptr_t)conn);
    clientWantsImage = 1;
}
예제 #12
0
static void send_to_all_websockets(const char * data, int data_len) {

    int i;

    for (i=0;i<MAX_NUM_OF_WEBSOCKS;i++) {
        if (socketList[i] && (socketList[i]->webSockState==2)) {
            mg_websocket_write(socketList[i]->conn, WEBSOCKET_OPCODE_TEXT, data, data_len);
        }
    }
}
예제 #13
0
void websocket_server_ready(struct mg_connection * conn, void * _ignored)
#endif
{
    printf("Server: Websocket ready\n");

    /* Send websocket welcome message */
    mg_lock_connection(conn);
    mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, websocket_welcome_msg, websocket_welcome_msg_len);
    mg_unlock_connection(conn);
}
예제 #14
0
int Server::ServeWebsocketRequest(struct mg_connection *conn)
{
	// Most browsers send an empty "heartbeat" to keep the connection open
	if (conn->content_len == 0)
		return MG_TRUE;
	// Echo
	printf("Websocket %p request %s of len %d\n", conn, conn->content, conn->content_len);
	mg_websocket_write(conn, 1, conn->content, conn->content_len);
    return MG_TRUE;
}
예제 #15
0
int websocket_server_data(struct mg_connection * conn, int bits, char *data, size_t data_len, void *_ignored)
#endif
{
    printf("Server: Got %u bytes from the client\n", data_len);

    if (data_len<3 || 0!=memcmp(data, "bye", 3)) {
        /* Send websocket acknowledge message */
        mg_lock_connection(conn);
        mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, websocket_acknowledge_msg, websocket_acknowledge_msg_len);
        mg_unlock_connection(conn);
    } else {
        /* Send websocket acknowledge message */
        mg_lock_connection(conn);
        mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, websocket_goodbye_msg, websocket_goodbye_msg_len);
        mg_unlock_connection(conn);
    }

    return 1; /* return 1 to keep the connetion open */
}
예제 #16
0
// Web Socket Handlers
// ----------------------------------------------------------------------------
void websocket_ready_handler(mg_connection *conn)
{
   //mg_request_info *pRequestInfo = mg_get_request_info(conn);

   //
   std::cout << "Mongoose has started" << std::endl;

   const char *message = "Server Ready !!";
   mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, message, strlen(message));

}
예제 #17
0
// Arguments:
//   flags: first byte of websocket frame, see websocket RFC,
//          http://tools.ietf.org/html/rfc6455, section 5.2
//   data, data_len: payload data. Mask, if any, is already applied.
int web_engine::websocket_data_handler(struct mg_connection *conn, int flags,
									char *data, size_t data_len)
{
	// just Echo example for now
	if ((flags & 0x0f) == WEBSOCKET_OPCODE_TEXT)
		mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, data, data_len);

	// Returning zero means stoping websocket conversation.
	// Close the conversation if client has sent us "exit" string.
	return memcmp(data, "exit", 4);
}
예제 #18
0
void web_engine::close()
{
	m_exiting_core = 1;
	osd_sleep(osd_ticks_per_second()/5);
	for (simple_list_wrapper<mg_connection> *curitem = m_websockets.first(); curitem != NULL; curitem = curitem->next())
	{
		mg_websocket_write(curitem->object(), WEBSOCKET_OPCODE_CONNECTION_CLOSE, NULL, 0);
	}
	// Stop the server.
	mg_stop(m_ctx);
}
예제 #19
0
파일: webengine.c 프로젝트: relimited/mame
void web_engine::push_message(const char *message)
{
	struct mg_connection *c;
	if (m_server!=NULL) {
		// Iterate over all connections, and push current time message to websocket ones.
		for (c = mg_next(m_server, NULL); c != NULL; c = mg_next(m_server, c)) {
			if (c->is_websocket) {
				mg_websocket_write(c, 1, message, strlen(message));
			}
		}
	}
}
예제 #20
0
static void push_message(struct mg_server *server, time_t current_time) {
  struct mg_connection *c;
  char buf[20];
  int len = sprintf(buf, "%lu", (unsigned long) current_time);

  // Iterate over all connections, and push current time message to websocket ones.
  for (c = mg_next(server, NULL); c != NULL; c = mg_next(server, c)) {
    if (c->is_websocket) {
      mg_websocket_write(c, 1, buf, len);
    }
  }
}
예제 #21
0
void WebAccess::slotFramePageChanged(int pageNum)
{
    if (m_conn == NULL)
        return;

    VCWidget *frame = (VCWidget *)sender();

    QString wsMessage = QString("%1|FRAME|%2").arg(frame->id()).arg(pageNum);
    QByteArray ba = wsMessage.toUtf8();

    mg_websocket_write(m_conn, WEBSOCKET_OPCODE_TEXT, ba.data(), ba.length());
}
예제 #22
0
// This handler is called for each incoming websocket frame, one or more
// times for connection lifetime.
static int handler(struct mg_connection *conn) {
  static const char oops[] = "HTTP/1.0 200 OK\r\n\r\nwebsocket data expected\n";

  if (!conn->is_websocket) {
    mg_write(conn, oops, sizeof(oops) - 1);
    return 1;
  }

  mg_websocket_write(conn, 1, conn->content, conn->content_len);

  return conn->content_len == 4 && !memcmp(conn->content, "exit", 4);
}
예제 #23
0
    void WebSocket::send(string data, int opcode)
    {
        if (isClosed()) {
            return;
        }

        mutex.lock();
        if (!mg_websocket_write(connection, opcode, data.c_str(), data.size())) {
            closed = true;
        }
        mutex.unlock();
    }
예제 #24
0
// sent direct to mg_connection
void send_msg_mc(struct mg_connection *mc, const char *msg, ...)
{
	va_list ap;
	char *s;

	va_start(ap, msg);
	vasprintf(&s, msg, ap);
	va_end(ap);
printf("send_msg_mc: <%s>\n", s);
	mg_websocket_write(mc, WS_OPCODE_BINARY, s, strlen(s));
	free(s);
}
예제 #25
0
void
WebSocketReadyHandler(struct mg_connection *conn, void *cbdata)
{
	const char *text = "Hello from the websocket ready handler";
	struct t_ws_client *client = mg_get_user_connection_data(conn);

	mg_websocket_write(conn, WEBSOCKET_OPCODE_TEXT, text, strlen(text));
	fprintf(stdout, "Greeting message sent to websocket client\r\n\r\n");
	ASSERT(client->conn == conn);
	ASSERT(client->state == 1);

	client->state = 2;
}
예제 #26
0
static int send_reply(struct mg_connection *conn) {
  if (conn->is_websocket) {
    // This handler is called for each incoming websocket frame, one or more
    // times for connection lifetime.
    // Echo websocket data back to the client.
    mg_websocket_write(conn, 1, conn->content, conn->content_len);
    return conn->content_len == 4 && !memcmp(conn->content, "exit", 4) ?
      MG_FALSE : MG_TRUE;
  } else {
    mg_send_file(conn, "index.html", NULL);
    return MG_MORE;
  }
}
예제 #27
0
int WebController::PushClientData(int opCode, const char *data , size_t data_len){
  struct mg_connection *c = NULL;
  int nrOfClients = 0;
  // Iterate over all connections, and push current time message to websocket ones.

  for (c = mg_next(server, c); c != NULL; c = mg_next(server, c)) {
    if (c->is_websocket) {
      mg_websocket_write(c, opCode, data, data_len);
      nrOfClients++;
    }
  }
  return nrOfClients;
}
예제 #28
0
static void websock_server_ready(struct mg_connection *conn, void *udata)
{
	ck_assert_ptr_eq((void *)udata, (void *)7531);
	printf("Server: Websocket ready\n");

	/* Send websocket welcome message */
	mg_lock_connection(conn);
	mg_websocket_write(conn,
	                   WEBSOCKET_OPCODE_TEXT,
	                   websocket_welcome_msg,
	                   websocket_welcome_msg_len);
	mg_unlock_connection(conn);

	printf("Server: Websocket ready X\n");
}
예제 #29
0
int ext_send_msg(int rx_chan, bool debug, const char *msg, ...)
{
	va_list ap;
	char *s;

	conn_t *conn = ext_users[rx_chan].conn;
	if (!conn || !conn->mc) return -1;
	va_start(ap, msg);
	vasprintf(&s, msg, ap);
	va_end(ap);
	if (debug) printf("ext_send_msg: RX%d-%p <%s>\n", rx_chan, conn, s);
	mg_websocket_write(conn->mc, WS_OPCODE_BINARY, s, strlen(s));
	free(s);
	return 0;
}
예제 #30
0
파일: App.cpp 프로젝트: jackpoz/G3D-backup
bool App::onEvent(const GEvent& event) {
    // Handle super-class events
    if (GApp::onEvent(event)) { return true; }

    if ((event.type == GEventType::KEY_DOWN) && (event.key.keysym.sym == 'p')) {
        // Send a message to the clients
        clientSetMutex.lock();
        for (Set<struct mg_connection*>::Iterator it = clientSet.begin(); it.isValid(); ++it) {
            mg_connection* conn = *it;
            mg_websocket_write(conn, 0x1, "{\"type\": 0, \"value\": \"how are you?\"}");
        }
        clientSetMutex.unlock();
        return true;
    }

    return false;
}