Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TCP/IP server using a main loop
# adapted from http://roscidus.com/desktop/node/413
import socket
import gobject
def server(host, port):
'''Initialize server and start listening.'''
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(1)
print "Listening..."
gobject.io_add_watch(sock, gobject.IO_IN, listener)
def listener(sock, *args):
'''Asynchronous connection listener. Starts a handler for each connection.'''
conn, addr = sock.accept()
print "Connected"
gobject.io_add_watch(conn, gobject.IO_IN, handler)
return True
def handler(conn, *args):
'''Asynchronous connection handler. Processes each line from the socket.'''
line = conn.recv(4096)
if len(line) > 0:
print "Received", line
conn.send(line + "!!!")
return True
else:
print "Connection closed."
return False
def client(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.send('Hello, world')
data = sock.recv(1024)
print data
sock.close()
import sys
if sys.argv[1] == "server":
server('', 50007)
gobject.MainLoop().run()
else:
client('', 50007)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.