Skip to content

Instantly share code, notes, and snippets.

@baogorek
Last active August 29, 2015 13:56
Show Gist options
  • Save baogorek/9013206 to your computer and use it in GitHub Desktop.
Save baogorek/9013206 to your computer and use it in GitHub Desktop.
A demonstration of socket programming. Open up two python shells and follow the instructions below. You'll send a message from one shell to the other using sockets! This was motivated by the Python sockets overview at http://docs.python.org/3.1/howto/sockets.html.
# Open two python shells
# Shell 1 will be our server, Shell 2 will be our client
##### In Shell 1 #####
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("127.0.0.1", 5000))
server_socket.listen(5) # Max 5 connect requests in queue
# It's strange that the sole purpose of server sockets is to create client sockets, on the server
# Shell 1 will seem to hang after running this line
(client_socket_on_server, address) = server_socket.accept()
##### In Shell 2 #####
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 5000))
##### In Shell 1 #####
# Which is now back in your control
client_socket_on_server.send("hey")
##### In Shell 2 #####
client_socket.recv(3) # three characters in 'hey'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment