TCP/IP in Python
Some notes on how TCP/IP works in Python (2.7).
Basic TCP client
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
try:
# Send data
message = 'This is the message. It will be repeated.'
print >>sys.stderr, 'sending "%s"' % message
sock.sendall(message)
# Look for the response
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print >>sys.stderr, 'received "%s"' % data
finally:
print >>sys.stderr, 'closing socket'
sock.close()
This client is simple and easy to use but I need something that would not block at all. To achieve this Python has a feature called select that can be used on stream like object that have a file descriptor. This selector can be used to check if the selector object has data ready for reading, writing or an exceptional condition (exceptional conditions not covered here).
import select
import socket
import sys
service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print >> sys.stderr, 'connecting to %s port %s' % server_address
service.connect(server_address)
This beginning stays the same but now the method to receive has changed.
r, w, e = select.select([service], [], [], 0.0)
if r: # There is something to read
data = service.recv(256)
character = 'ChrBrad0'
bmlMessage = data