Skip to content

Instantly share code, notes, and snippets.

Created June 20, 2010 06:40
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 mblondel/445616 to your computer and use it in GitHub Desktop.
Save mblondel/445616 to your computer and use it in GitHub Desktop.
TCP/IP server using a main loop
# adapted from
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))
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
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
import sys
if sys.argv[1] == "server":
server('', 50007)
client('', 50007)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment