Skip to content

Instantly share code, notes, and snippets.

@rekyuu
Last active November 8, 2015 01:33
Show Gist options
  • Save rekyuu/3ecec39ed5be257d82cb to your computer and use it in GitHub Desktop.
Save rekyuu/3ecec39ed5be257d82cb to your computer and use it in GitHub Desktop.
Basic socket communication in Python
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 4560
# Connects to the server.
s.connect((host, port))
print('Connected.')
# Initiates the conversation.
s.send(bytes('PING', 'utf8'))
print('>', 'PING')
# Loop to listen for incoming data.
while True:
try:
data = s.recv(4096).decode('utf8')
# Quits if it receives 'PONG'.
if data == 'PONG':
print('<', data)
s.close()
break
except socket.error:
print('Socket died.')
raise
except socket.timeout:
print('Socket timeout.')
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 4560
# Binds the server to address and port.
s.bind((host, port))
# Listens for a max of 5 clients.
s.listen(5)
while True:
# Accepts a connection.
c, addr = s.accept()
print('Recieved connection from', addr)
# Receives data from the client.
data = c.recv(4096).decode('utf8')
# Responds with a 'PONG'.
if data == 'PING':
print('<', data)
c.send(bytes('PONG', 'utf8'))
print('>', 'PONG')
# Closes the connection.
c.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment