Thursday 2 June 2016

A simple (web)socket server with python

Below is a simple socket or u can say websocket server in python.
Used this to test apache websocket proxy for one project.
Though to textend it a bit so i can play with it using telnet. 
The server uses python threads which is a good place to learn how python threads work when tied to sockets.
The thread runs the handle function and passes client connection socket returned by accept.
Also needed to do some string operations to make the message going to the telnet client look good.
Will be extending this more and will try to link it to a JS front end and see how can i make use of that.

Python is really good :)


[root@Vardamir ~]# cat pyws.py
#!/usr/bin/env python

import socket, threading, time

def handle(s):
  print "new connction"
  print "connection detailes:"
  print repr(s.recv(4096))
  s.send('''
HTTP/1.1 101 Web Socket Protocol Handshake\r
Upgrade: WebSocket\r
Connection: Upgrade\r
WebSocket-Origin: http://localhost:9999\r
WebSocket-Location: ws://localhost:9999/\r
WebSocket-Protocol: sample
  '''.strip() + '\r\n\r\n')
  time.sleep(1)
  s.send('\x00hello_world\xff')
  time.sleep(1)
  s.send('\r\n')
  time.sleep(1)
  s.send('This is a test websocket server in python')
  s.send('\r\n')
  time.sleep(1)
  s.send('\r\n')
 
  while 1:
        data=str(repr(s.recv(4096)))
        data=data[1:-5]
        print data
        time.sleep(1)
        s.send("hello i got this "+data+" from u :)")
        s.send('\r\n')
        s.close()
        break


s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 9999));
s.listen(1);
print "Simple Server started on port 9999"
while 1:
  clientconn , clientaddr = s.accept();
  clientThread = threading.Thread(target=handle, args=(clientconn, ))
  clientThread.start()

No comments:

Post a Comment