Simple websocket client example
Dependencies: WIFI_API_32kRAM WebSocketClient mbed
This sample code work with following Websocket Echo Server implementation using Python (tornado package needed). The echo server will wait for a message to be received and then echo back the message reversed. Details about the connection will be printed to the terminal.
import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import socket ''' This is a simple Websocket Echo server that uses the Tornado websocket handler. Please run `pip install tornado` with python of version 2.7.9 or greater to install tornado. This program will echo back the reverse of whatever it recieves. Messages are output to the terminal for debuggin purposes. ''' class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print 'new connection' def on_message(self, message): print 'message received: %s' % message # Reverse Message and send it back print 'sending back message: %s' % message[::-1] self.write_message(message[::-1]) def on_close(self): print 'connection closed' def check_origin(self, origin): return True application = tornado.web.Application([ (r'/ws', WSHandler), ]) if __name__ == "__main__": http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8888) myIP = socket.gethostbyname(socket.gethostname()) print '*** Websocket Server Started at %s***' % myIP tornado.ioloop.IOLoop.instance().start()
Revision 1:610f3dc5679e, committed 2015-10-27
- Comitter:
- wgd8700
- Date:
- Tue Oct 27 10:03:33 2015 +0000
- Parent:
- 0:47ec083185d0
- Commit message:
- Add ws.read function
Changed in this revision
WIFI_API_32kRAM.lib | Show annotated file Show diff for this revision Revisions of this file |
main.cpp | Show annotated file Show diff for this revision Revisions of this file |
--- a/WIFI_API_32kRAM.lib Wed Oct 07 05:16:10 2015 +0000 +++ b/WIFI_API_32kRAM.lib Tue Oct 27 10:03:33 2015 +0000 @@ -1,1 +1,1 @@ -http://developer.mbed.org/teams/Delta/code/WIFI_API_32kRAM/#8d8c2064be73 +http://developer.mbed.org/teams/Delta/code/WIFI_API_32kRAM/#d4e992043905
--- a/main.cpp Wed Oct 07 05:16:10 2015 +0000 +++ b/main.cpp Tue Oct 27 10:03:33 2015 +0000 @@ -8,7 +8,7 @@ Serial pc(USBTX, USBRX); int main() { - char recv[30]; + char recv[50]; pc.baud(115200); pc.printf("Init...\n"); @@ -17,17 +17,20 @@ eth.init(); //Use DHCP // set given SSID and PW as the highest priority - wifi.setNetwork("Tsungta_iPhone", "icq87001", 0); + //wifi.setNetwork("Tsungta_iPhone", "icq87001", 0); + wifi.setNetwork("GainSpan_JS", "Delta9999", 0); eth.connect(40000); pc.printf("IP Address:%s\n",eth.getIPAddress()); pc.printf("MAC Address:%s\n",eth.getMACAddress()); - Websocket ws("ws://172.20.10.11:8888/ws"); + Websocket ws("ws://192.168.15.105:8888/ws"); ws.connect(); while (1) { ws.send("WebSocket Hello World over Ethernet"); - wait(1.0); + ws.read(recv); + pc.printf("read: %s\n", recv); + wait(1.0); } } \ No newline at end of file