Sending Streaming Data
sSock = socket(AF_INET, SOCK_STREAM) sSock.connect((serverHost, serverPort)) line = raw_input("Send to %s: " % (serverHost)) sSock.send(line+'\n') data = sSock.recv(1024)
To send streaming data to the streaming server described in the previous task, first create the client socket by calling socket(family, type [, proto]), which creates and returns a new socket.
Once the streaming client-side socket has been created, it can connect to the streaming server using the connect(address) method, where address refers to a tuple in the form of (hostname, port).
After the streaming client-side socket has connected to the server-side socket, data can be streamed to the server by formatting a stream of data that ends with the newline character and sending it to the server using the send(string [,flags]) method.
A response from the server is received from the socket using the recv(buffsize [,flags]) method.
import sys from socket import * serverHost = 'localhost' serverPort = 50008 if len(sys.argv) > 1: serverHost = sys.argv[1] #Create socket sSock = socket(AF_INET, SOCK_STREAM) #Connect to server sSock.connect((serverHost, serverPort)) #Stream data to server. line = "" while line != 'bye': line = raw_input("Send to %s: " % (serverHost)) sSock.send(line+'\n') data = sSock.recv(1024) print 'data' sSock.shutdown(0) sSock.close()
stream_client.py
Send to 137.65.76.28: Hello '137.65.77.28: 6 bytes received.' Send to 137.65.76.28: Here is today's weather. '137.65.77.28: 25 bytes received.' Send to 137.65.76.28: Sunny '137.65.77.28: 6 bytes received.' Send to 137.65.76.28: High: 75 '137.65.77.28: 9 bytes received.' Send to 137.65.76.28: Low: 58 '137.65.77.28: 8 bytes received.' Send to 137.65.76.28: bye '137.65.77.28: 4 bytes received.'
Output from stream_client.py code