Skip to content

Instantly share code, notes, and snippets.

@nattomi
Last active December 19, 2016 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nattomi/438f724497802c3ac946 to your computer and use it in GitHub Desktop.
Save nattomi/438f724497802c3ac946 to your computer and use it in GitHub Desktop.
poco c++ websocket client pushing data to autobahn python websocket server

Client: C++ (POCO)

Feeds data continuously to a websocket server. Relies on the POCO library.

Installing POCO
cd /tmp
wget http://pocoproject.org/releases/poco-1.6.0/poco-1.6.0.tar.gz
tar -xzvf poco-1.6.0.tar.gz
cd poco-1.6.0
./configure --no-tests --no-samples --prefix=/usr
make -s
sudo make -s install
Compiling client.cpp
g++ client.cpp -lPocoNet -o client

Server: Python (Autobahn)

This server is configured so that if it gets a message from localhost then it redisributes it immediately to any other connected clients.

Client: C (nopoll)

client_nopoll.c is another example of a websocket client based on the nopoll library written in pure C.

Installing nopoll

installing dependency:

sudo apt-get install libssl-dev 

Then:

cd /tmp
wget http://www.aspl.es/nopoll/downloads/nopoll-0.2.7.b164.tar.gz
tar -xzvf nopoll-0.2.7.b164.tar.gz
cd nopoll-0.2.7.b164
./configure --prefix=/usr
make

At this point you can navigate to the 'test' directory and run the examples nopoll-regression-listener and nopoll-regression-client in separate terminals. If it looks ok, then it only remains to

sudo make install
Compiling client_nopoll.c
g++ client_nopoll.c -I/usr/include/nopoll -lnopoll -o client_nopoll

You can test client_nopoll via starting the nopoll-regression-listener (a server) in the test folder.

#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/WebSocket.h"
#include "Poco/Net/HTTPClientSession.h"
#include <iostream>
#include <sstream> // for converting time_t to const char*
#include <string> // for converting time_t to const char*
#include <ctime> // for getting current time
using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::Net::WebSocket;
int main(int args,char **argv)
{
HTTPClientSession cs("127.0.0.1",9000);
HTTPRequest request(HTTPRequest::HTTP_GET, "/?encoding=text",HTTPMessage::HTTP_1_1);
HTTPResponse response;
try {
WebSocket* m_psock = new WebSocket(cs, request, response);
std::ostringstream strs;
while(true) { // sending data to websocket server forever
time_t t = time(NULL);
strs << t;
const char* testStr = strs.str().c_str();
int len=m_psock->sendFrame(testStr,strlen(testStr),WebSocket::FRAME_TEXT);
std::cout << "Sent bytes " << len << std::endl;
strs.str(std::string());
sleep(1);
}
m_psock->close();
} catch (std::exception &e) {
std::cout << "Exception " << e.what();
}
return 0;
}
#include <nopoll.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
int main(int argc,char **argv) {
noPollCtx * ctx = nopoll_ctx_new ();
if (! ctx) {
printf("Error creating nopoll context\n");
return nopoll_false;
}
// call to create a connection
noPollConn * conn = nopoll_conn_new (ctx, "localhost", "1234", NULL, NULL, NULL, NULL);
if (! nopoll_conn_is_ok (conn)) {
printf("Error connecting to server\n");
return nopoll_false;
}
char str[20];
for(int i=0;i<15;i++) {
sprintf(str, "Test: %d", i);
nopoll_conn_send_text (conn, str, strlen(str));
printf("%d\n",i);
sleep(1);
}
nopoll_ctx_unref (ctx);
return 0;
}
import sys
from twisted.internet import reactor
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File
from autobahn.twisted.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
class BroadcastServerProtocol(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
def onMessage(self, payload, isBinary):
if not isBinary:
msg = "{} from {}".format(payload.decode('utf8'), self.peer)
peer = self.peer
client_ip = peer.split(':')[1]
if client_ip == "127.0.0.1":
self.factory.broadcast(msg)
def connectionLost(self, reason):
WebSocketServerProtocol.connectionLost(self, reason)
self.factory.unregister(self)
class BroadcastServerFactory(WebSocketServerFactory):
"""
Simple broadcast server broadcasting any message it receives to all
currently connected clients.
"""
def __init__(self, url, debug = False, debugCodePaths = False):
WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)
self.clients = []
def register(self, client):
if not client in self.clients:
print("registered client {}".format(client.peer))
self.clients.append(client)
def unregister(self, client):
if client in self.clients:
print("unregistered client {}".format(client.peer))
self.clients.remove(client)
def broadcast(self, msg):
print("broadcasting message '{}' ..".format(msg))
for c in self.clients:
c.sendMessage(msg.encode('utf8'))
print("message sent to {}".format(c.peer))
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'debug':
log.startLogging(sys.stdout)
debug = True
else:
debug = False
factory = BroadcastServerFactory("ws://aero.nck.ggki.hu:9000", debug=False)
factory.protocol = BroadcastServerProtocol
reactor.listenTCP(9000, factory)
reactor.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment