Created
March 17, 2012 08:41
-
-
Save techtonik/2056748 to your computer and use it in GitHub Desktop.
Python - socket - Client/server example in one thread
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
import socket | |
if __name__ == '__main__': | |
# socket read/write testing - client and server in one thread | |
# (techtonik): the stuff below is placed into public domain | |
print "-- Testing standard Python socket interface --" | |
address = ("127.0.0.1", 9999) | |
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
server.setblocking(0) | |
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
server.bind( address ) | |
server.listen(2) | |
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
client.connect( address ) | |
client.send("data to be catched") | |
# accepted server socket is the one we can read from | |
# note that it is different from server socket | |
accsock, addr = server.accept() | |
print '..got "%s" from %s' % (accsock.recv(4096), addr) | |
client.send("more data for recv") | |
print '..got "%s" from %s' % (accsock.recv(4096), addr) | |
# accsock.close() | |
# client.send("more data for recv") | |
#socket.error: [Errno 9] Bad file descriptor | |
# accsock, addr = server.accept() | |
#socket.error: [Errno 11] Resource temporarily unavailable | |
client.close() | |
server.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment