void WebSocketQueue::work() { std::lock_guard<std::mutex> guard(mutex_); //TODO: Check if any out messages, HAAAAAACK //std::cout << "outMessages.size()" << outMessages.size() << std::endl; //std::size_t outMessageCount = outMessages_.size(); while (!outMessages_.empty()) { libwebsocket_callback_on_writable_all_protocol(webSocketProtocol); messageSent_ = false; libwebsocket_service(context_, 0); if (!messageSent_) break; } //Cleanup for (OutMessage& message : outMessages_) { message.keepDestinations(sessions_); } auto newEnd = std::remove_if(outMessages_.begin(), outMessages_.end(), [](OutMessage const& message) { return message.destinations().empty(); }); outMessages_.erase(newEnd, outMessages_.end()); libwebsocket_service(context_, 10); }
bool WebSocketClient2::on_wsc_service_loop() { int iret = 0; static int tcnt = 0; qLogx()<<"ws client serviceing..."; iret = libwebsocket_service(this->m_lws_ctx, 2000); qLogx()<<iret; // qDebug()<<__FILE__<<__LINE__<<__FUNCTION__; if (iret == 0) { // ok, success } else { // listen socket deak qDebug()<<__FILE__<<__LINE__<<__FUNCTION__<<"Listen socket maybe dead." <<"Need restart this server."; } if (this->m_wsi != NULL) { // QString a = QString("[abcdddddd %1]").arg(++tcnt); // qLogx()<<"Sending :"<<a; // this->sendMessage(a.toAscii()); } return true; }
//-------------------------------------------------------------- void Client::threadedFunction(){ while ( isThreadRunning() ){ for (int i=0; i<protocols.size(); ++i){ if (protocols[i].second != NULL){ //lock(); protocols[i].second->execute(); //unlock(); } } if (context != NULL && lwsconnection != NULL){ //libwebsocket_callback_on_writable(context,lwsconnection); connection->update(); if (lock()) { int n = libwebsocket_service(context, waitMillis); unlock(); } } else { stopThread(); if ( context != NULL ){ closeAndFree = true; libwebsocket_context_destroy( context ); context = NULL; lwsconnection = NULL; } if (connection != NULL){ connection = NULL; } } } }
static bool createWebsocketContext(int port) { assert(!wsState); wsState = new WSState; struct lws_context_creation_info info; memset(&info, 0, sizeof(info)); if (port == PORT_ANY) { info.port = CONTEXT_PORT_NO_LISTEN; } else { info.port = port; } info.protocols = protocols; info.gid = -1; info.uid = -1; STUBBED("TODO: put keepalive stuff in cvars"); info.ka_time = 5; info.ka_probes = 3; info.ka_interval = 1; wsState->websocketContext = libwebsocket_create_context(&info); if (!wsState->websocketContext) { delete wsState; wsState = NULL; return false; } int retval = libwebsocket_service(wsState->websocketContext, 0); Com_Printf("libwebsocket_service returned %d\n", LOG_NET, retval); return true; }
int main() { struct lws_context_creation_info info; char *port; signal(SIGINT, sighandler); port = getenv("PORT"); memset(&info, 0, sizeof info); info.port = (port == NULL) ? DEFAULT_PORT : atoi(port); info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.gid = -1; info.uid = -1; context = libwebsocket_create_context(&info); if (context == NULL) { lwsl_err("libwebsocket init failed\n"); return -1; } while (!force_exit) { libwebsocket_service(context, 50); } libwebsocket_context_destroy(context); lwsl_notice("exited cleanly\n"); return 0; }
int websocket_recv(int socket, unsigned char *data, size_t maxsize, struct sockaddr_in *sockaddrbuf, size_t fromLen) { libwebsocket_context *context = contexts[socket].context; if(context == NULL) return -1; int n = libwebsocket_service(context, 0); if(n < 0) return n; context_data *ctx_data = (context_data *)libwebsocket_context_user(context); websocket_chunk *chunk = (websocket_chunk *)ctx_data->recv_buffer.First(); if(chunk == 0) return 0; if(maxsize >= chunk->size - chunk->read) { int len = chunk->size - chunk->read; memcpy(data, &chunk->data[chunk->read], len); memcpy(sockaddrbuf, &chunk->addr, fromLen); ctx_data->recv_buffer.PopFirst(); return len; } else { memcpy(data, &chunk->data[chunk->read], maxsize); memcpy(sockaddrbuf, &chunk->addr, fromLen); chunk->read += maxsize; return maxsize; } }
int main () { struct libwebsocket_context *context; struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = 7681; info.iface = NULL; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; info.gid = -1; info.uid = -1; info.options = 0; context = libwebsocket_create_context(&info); printf ("starting server.\n"); while (1) { libwebsocket_service(context, 50); } libwebsocket_context_destroy(context); return 0; }
/* Thread */ void *janus_websockets_thread(void *data) { struct libwebsocket_context *service = (struct libwebsocket_context *)data; if(service == NULL) { JANUS_LOG(LOG_ERR, "Invalid service\n"); return NULL; } const char *type = NULL; if(service == wss) type = "WebSocket (Janus API)"; else if(service == swss) type = "Secure WebSocket (Janus API)"; else if(service == admin_wss) type = "WebSocket (Admin API)"; else if(service == admin_swss) type = "Secure WebSocket (Admin API)"; JANUS_LOG(LOG_INFO, "%s thread started\n", type); while(g_atomic_int_get(&initialized) && !g_atomic_int_get(&stopping)) { /* libwebsockets is single thread, we cycle through events here */ libwebsocket_service(service, 50); } /* Get rid of the WebSockets server */ libwebsocket_cancel_service(service); /* Done */ JANUS_LOG(LOG_INFO, "%s thread ended\n", type); return NULL; }
static bool tcod_pauseForMilliseconds(short milliseconds) { TCOD_mouse_t mouse; TCOD_console_flush(); TCOD_sys_sleep_milli((unsigned int) milliseconds); /* FIXME: lag? never heard of it! */ int n; n = libwebsocket_service(context, 0); if (bufferedKey.vk == TCODK_NONE) { bufferedKey = TCOD_console_check_for_keypress(TCOD_KEY_PRESSED); } if (missedMouse.lmb == 0 && missedMouse.rmb == 0) { /* FIXME mouse input */ //mouse = TCOD_mouse_get_status(); if (mouse.lbutton_pressed || mouse.rbutton_pressed) { missedMouse.x = mouse.cx; missedMouse.y = mouse.cy; if (mouse.lbutton_pressed) missedMouse.lmb = MOUSE_DOWN; if (mouse.rbutton_pressed) missedMouse.rmb = MOUSE_DOWN; } } /* return true if a new input event is available */ return (bufferedKey.vk != TCODK_NONE || missedMouse.lmb || missedMouse.rmb); }
int idaapi websocket_thread(void *) { struct libwebsocket_context* context; struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = 3003; info.iface = NULL; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.gid = -1; info.uid = -1; info.options = 0; // i assume this does the bind? context = libwebsocket_create_context(&info); if (context == NULL) { msg("websocket init failed\n"); return -1; } msg("yay websockets\n"); while (websockets_running) { libwebsocket_service(context, 50); } libwebsocket_context_destroy(context); return 0; }
void SignalingWebSocketServer::run() { while ( !bQuit ) { libwebsocket_service(context, 50); sig_thread->ProcessMessages(10); } usleep(10); libwebsocket_context_destroy(context); }
static unsigned WSServerThread(void *params) { WSServerThreadParams_t *vars = (WSServerThreadParams_t *)params; while (ws_shouldListen) { libwebsocket_service(vars->ctx, 16); //check for events every 16ms } delete vars; return 0; }
bool FWebSocketServer::Tick() { #if !PLATFORM_HTML5 { libwebsocket_service(Context, 0); libwebsocket_callback_on_writable_all_protocol(&Protocols[0]); } #endif return true; }
int main( void ) { int port = 8080; const char *interface = NULL; struct libwebsocket_context *context; struct lws_context_creation_info context_info; memset( &context_info, 0, sizeof( struct lws_context_creation_info ) ); context_info.port = 8080; context_info.iface = NULL; context_info.protocols = protocols; context_info.extensions = libwebsocket_get_internal_extensions(); context_info.ssl_cert_filepath = NULL; context_info.ssl_private_key_filepath = NULL; context_info.ssl_ca_filepath = NULL; context_info.ssl_cipher_list = NULL; context_info.http_proxy_address = NULL; context_info.http_proxy_port = 0; context_info.gid = -1; context_info.uid = -1; context_info.options = 0; context_info.user = NULL; context_info.ka_time = 0; context_info.ka_probes = 0; context_info.ka_interval = 0; const char *cert_path = NULL; const char *key_path = NULL; int opts = 0; // context = libwebsocket_create_context( port, interface, protocols, // libwebsocket_internal_extensions, // cert_path, key_path, -1, -1, opts ); context = libwebsocket_create_context( &context_info ); if ( context == NULL ) { fprintf( stderr, "libwebsocket init failed\n" ); return -1; } printf( "Starting server ...\n" ); while ( 1 ) { libwebsocket_service( context, 50 ); } libwebsocket_context_destroy( context ); return 0; }
uintptr_t WebSocketOpcode_processThread(void *opaquePointer) { WebSocketOpcode *self = opaquePointer; while (self->isRunning == 1) { libwebsocket_service(self->webSocket->context, 10); libwebsocket_callback_on_writable_all_protocol(self->webSocket->protocols); } return 0; }
int ws_service(){ /*returns immediately if no task is pending.*/ if(context){ int ans=libwebsocket_service(context, 0); if(ans<0){ ws_end(); context=0; } return ans; }else{ return -1; } }
int main() { if(!setlocale(LC_CTYPE, "en_US.UTF-8")) { fprintf(stderr, "Cannot set UTF-8 encoding. Please make sure that en_US.UTF-8 encoding is installed.\n"); } memset(data_to_send, 0, 16*sizeof(char*)); signal(SIGINT, sighandler); corefd=core_socket(); if(corefd == -1) { fprintf(stderr, "tapi2p core not running!\n"); return 1; } event_addlistener(ListPeers, &coreeventhandler, NULL); event_addlistener(FileList, &coreeventhandler, NULL); event_addlistener(Message, &coreeventhandler, NULL); event_addlistener(PeerConnected, &coreeventhandler, NULL); event_addlistener(PeerDisconnected, &coreeventhandler, NULL); event_addlistener(Status, &coreeventhandler, NULL); event_addlistener(GetPublicKey, &coreeventhandler, NULL); event_addlistener(AddPeer, &coreeventhandler, NULL); eventsystem_start(corefd); struct libwebsocket_context* ctx; struct lws_context_creation_info info; memset(&info, 0, sizeof(info)); info.port=7681; info.protocols=protocols; info.gid=-1; info.uid=-1; ctx = libwebsocket_create_context(&info); while(!ctx) { lwsl_err("libwebsocket init failed."); sleep(1); ctx = libwebsocket_create_context(&info); } lwsl_notice("tapi2p websocket server started.\n"); int n=0; while(n>=0 && run_server) { n=libwebsocket_service(ctx, 50); } eventsystem_stop(); return 0; }
bool Connection::sendPacket(const char *data, size_t length) { assert(wsi); assert(readyState == Open); assert(length < 16384); uint16_t l16 = length; memcpy(&sendBuf[LWS_SEND_BUFFER_PRE_PADDING], &l16, 2); memcpy(&sendBuf[LWS_SEND_BUFFER_PRE_PADDING + 2], data, length); // TODO: too many calls to libwebsocket_service here libwebsocket_service(wsState->websocketContext, 0); if (!writable) { // track socket writable status, only write when would not block // TODO: buffer or drop? return false; } int retval = libwebsocket_write(wsi, &sendBuf[LWS_SEND_BUFFER_PRE_PADDING], length + 2, LWS_WRITE_BINARY); if (retval < 0) { return false; } writable = false; libwebsocket_callback_on_writable(wsState->websocketContext, wsi); libwebsocket_service(wsState->websocketContext, 0); if (retval < length) { // partial send // TODO: handle this better, try to resend rest later STUBBED("resend"); return false; } return true; }
void NET_Sleep(int msec) { extern cvar_t *dedicated; //extern qboolean stdin_active; if (!server_port || !dedicated->intvalue) return; // we're not a server, just run full speed //Com_Printf ("NET_Sleep (%d)\n", LOG_GENERAL, msec); #ifndef EMSCRIPTEN libwebsocket_service(wsState->websocketContext, msec); #endif // EMSCRIPTEN }
uint32 FNetworkFileServerHttp::Run() { UE_LOG(LogFileServer, Display, TEXT("Unreal Network File Http Server is ready for client connections on port %d"), Port); // start servicing. // service libwebsocket context. while(!StopRequested.GetValue()) { // service libwebsocket, have a slight delay so it doesn't spin on zero load. libwebsocket_service(Context, 10); libwebsocket_callback_on_writable_all_protocol(&Protocols[0]); } UE_LOG(LogFileServer, Display, TEXT("Unreal Network File Http Server is now Shutting down ")); return true; }
void* HostProcess_WebSocketListener(void* stuff) { HostStuff* phoststuff=(HostStuff*)stuff; struct libwebsocket_context *context; int opts = 0; struct lws_context_creation_info info; memset(&info, 0, sizeof info); info.port = WEB_PORT; info.iface = 0; info.protocols = protocols; info.extensions = libwebsocket_get_internal_extensions(); info.ssl_cert_filepath = NULL; info.ssl_private_key_filepath = NULL; info.gid = -1; info.uid = -1; info.options = opts; info.user=phoststuff; context = libwebsocket_create_context(&info); if (context == NULL) { fprintf(stderr, "libwebsocket init failed\n"); return 0; } printf("starting server...\n"); // infinite loop, to end this server send SIGTERM. (CTRL+C) while (1) { libwebsocket_service(context, 50); // libwebsocket_service will process all waiting events with their // callback functions and then wait 50 ms. // (this is a single threaded webserver and this will keep our server // from generating load while there are not requests to process) } libwebsocket_context_destroy(context); return 0; }
//============================================================================== // WsInput //------------------------------------------------------------------------------ void WsInput::wsConnect(WsInput* wsinput) { libwebsocket_context *context; lws_context_creation_info info; int debug_level = 7; memset(&info,0,sizeof info); info.port = 7681; lws_set_log_level(debug_level,da); lwsl_notice("libwebsockets chat server -\n"); libwebsocket_protocols protocols[] = { { "input", WsInput::wsCallBackData, 0, 128 }, {NULL,NULL,0,0} /* terminator */ }; info.iface = nullptr; info.protocols = protocols; info.ssl_cert_filepath = nullptr; info.ssl_private_key_filepath = nullptr; info.gid = -1; info.uid = -1; info.options = 0; info.user = nullptr; context = libwebsocket_create_context(&info); for(;;) { int n = libwebsocket_service(context,10); if(n >= 0 && wsinput->_isend) { break; } } libwebsocket_context_destroy(context); wsinput->_isend = false; }
int WebSocket::onSubThreadLoop() { if (_readyState == kStateClosed || _readyState == kStateClosing) { libwebsocket_context_destroy(_wsContext); // return 1 to exit the loop. return 1; } if (_wsContext && _readyState != kStateClosed && _readyState != kStateClosing) { libwebsocket_service(_wsContext, 0); } // Sleep 50 ms std::this_thread::sleep_for(std::chrono::milliseconds(50)); // return 0 to continue the loop. return 0; }
static std::unique_ptr<Connection> createConnection(const netadr_t &to) { assert(wsState); char addrBuf[3 * 4 + 5]; snprintf(addrBuf, sizeof(addrBuf), "%u.%u.%u.%u", to.ip[0], to.ip[1], to.ip[2], to.ip[3]); struct libwebsocket *newWsi = libwebsocket_client_connect(wsState->websocketContext, addrBuf, ntohs(to.port), 0, "/", addrBuf, addrBuf, "quake2", -1); if (newWsi == NULL) { STUBBED("TODO: log connection create failure"); return std::unique_ptr<Connection>(); } libwebsocket_callback_on_writable(wsState->websocketContext, newWsi); STUBBED("TODO: unnecessary(?) libwebsocket_service"); libwebsocket_service(wsState->websocketContext, 0); std::unique_ptr<Connection> conn(new Connection(to, newWsi)); wsState->wsiLookup.emplace(newWsi, conn.get()); return conn; }
void FWebSocket::HandlePacket() { #if !PLATFORM_HTML5 { libwebsocket_service(Context, 0); if (!IsServerSide) libwebsocket_callback_on_writable_all_protocol(&Protocols[0]); } #endif #if PLATFORM_HTML5 fd_set Fdr; fd_set Fdw; int Res; // make sure that server.fd is ready to read / write FD_ZERO(&Fdr); FD_ZERO(&Fdw); FD_SET(SockFd, &Fdr); FD_SET(SockFd, &Fdw); Res = select(64, &Fdr, &Fdw, NULL, NULL); if (Res == -1) { UE_LOG(LogHTML5Networking, Warning, TEXT("Select Failed!")); return; } if (FD_ISSET(SockFd, &Fdr)) { // we can read! OnRawRecieve(NULL, NULL); } if (FD_ISSET(SockFd, &Fdw)) { // we can write OnRawWebSocketWritable(NULL); } #endif }
//-------------------------------------------------------------- void Server::threadedFunction() { while (isThreadRunning()) { // update all connections for (int i=0; i<connections.size(); i++){ if ( connections[i] ){ connections[i]->update(); } } for (int i=0; i<protocols.size(); ++i){ if (protocols[i].second != NULL){ //lock(); protocols[i].second->execute(); //unlock(); } } lock(); libwebsocket_service(context, waitMillis); unlock(); } }
int main(void) { // server url will be http://localhost:9000 int port = 9000; const char *interface = NULL; struct libwebsocket_context *context; // we're not using ssl const char *cert_path = NULL; const char *key_path = NULL; // no special options int opts = 0; // create libwebsocket context representing this server context = libwebsocket_create_context(port, interface, protocols, libwebsocket_internal_extensions, cert_path, key_path, -1, -1, opts, NULL); if (context == NULL) { fprintf(stderr, "libwebsocket init failed\n"); return -1; } printf("starting server...\n"); // infinite loop, to end this server send SIGTERM. (CTRL+C) while (1) { libwebsocket_service(context, 50); // libwebsocket_service will process all waiting events with their // callback functions and then wait 50 ms. // (this is a single threaded webserver and this will keep our server // from generating load while there are not requests to process) } libwebsocket_context_destroy(context); return 0; }
int WebSocket::onSubThreadLoop() { if (_readyState == kStateClosed || _readyState == kStateClosing) { libwebsocket_context_destroy(_wsContext); // return 1 to exit the loop. return 1; } if (_wsContext && _readyState != kStateClosed && _readyState != kStateClosing) { libwebsocket_service(_wsContext, 0); } // Sleep 50 ms #ifdef WIN32 Sleep(50); #else usleep(50000); #endif // return 0 to continue the loop. return 0; }
int NET_GetPacket (netsrc_t sock, netadr_t *net_from, sizebuf_t *net_message) { if (NET_GetLoopPacket (sock, net_from, net_message)) return 1; if (!wsState) { // not initialized yet return 0; } if (wsState->pendingData.empty()) { #ifdef EMSCRIPTEN return 0; #else // EMSCRIPTEN libwebsocket_service(wsState->websocketContext, 0); #endif // EMSCRIPTEN } // don't iterate via reference, recvPacket will alter the data structure for (auto conn : wsState->pendingData) { if (conn->recvPacket(net_message)) { *net_from = conn->addr; net_packets_in++; net_total_in += net_message->cursize; return 1; } // not enough data for a complete packet, try next connection } return 0; }
int main(int argc, char **argv) { int n = 0; int ret = 0; // int port = 8543; int port = 9000; int use_ssl = 0; struct libwebsocket_context *context; // const char *address="192.168.6.176"; const char *address="192.168.6.114"; struct libwebsocket *wsi_dumb; int ietf_version = -1; /* latest */ struct lws_context_creation_info info; memset(&info, 0, sizeof info); fprintf(stderr, "DTS2B websockets client\n" "(C) Copyright 2014-2015 Mleaf_HEXI <*****@*****.**> " "licensed under LGPL2.1\n"); /* * create the websockets context. This tracks open connections and * knows how to route any traffic and which protocol version to use, * and if each connection is client or server side. * * For this client-only demo, we tell it to not listen on any port. */ info.port = CONTEXT_PORT_NO_LISTEN; info.protocols = protocols; #ifndef LWS_NO_EXTENSIONS info.extensions = libwebsocket_get_internal_extensions(); #endif info.gid = -1; info.uid = -1; context = libwebsocket_create_context(&info); if (context == NULL) { fprintf(stderr, "Creating libwebsocket context failed\n"); return 1; } /* create a client websocket using dumb increment protocol */ /* TITLE: libwebsocket_client_connect - Connect to another websocket server struct libwebsocket * libwebsocket_client_connect (struct libwebsocket_context * context, const char * address, int port, int ssl_connection, const char * path, const char * host, const char * origin, const char * protocol, int ietf_version_or_minus_one) Arguments context Websocket context address Remote server address, eg, "myserver.com" port Port to connect to on the remote server, eg, 80 ssl_connection 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self signed certs path Websocket path on server host Hostname on server origin Socket origin name protocol Comma-separated list of protocols being asked for from the server, or just one. The server will pick the one it likes best. ietf_version_or_minus_one -1 to ask to connect using the default, latest protocol supported, or the specific protocol ordinal Description This function creates a connection to a remote server */ fprintf(stderr, "Connecting to %s:%u\n", address, port); wsi_dumb = libwebsocket_client_connect(context, address, port, use_ssl, "/websocket/uclient/MOCK_DTS2B_ACCESS_CODE_1234567890", address,"origin", protocols[0].name, ietf_version); if (wsi_dumb == NULL) { fprintf(stderr, "libwebsocket connect failed\n"); ret = 1; goto bail; } fprintf(stderr, "Waiting for connect...\n"); sqlite3_test();//sqlite3数据库测试 /* * sit there servicing the websocket context to handle incoming * packets, and drawing random circles on the mirror protocol websocket * nothing happens until the client websocket connection is * asynchronously established */ n = 0; while (n >= 0 && !was_closed && !force_exit) { n = libwebsocket_service(context, 10); if (n < 0) continue; if (wsi_mirror) continue; } bail: fprintf(stderr, "Exiting\n"); libwebsocket_context_destroy(context); return 1; }