Created
June 20, 2010 06:40
-
-
Save mblondel/445616 to your computer and use it in GitHub Desktop.
TCP/IP server using a main loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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