Opening a Client-Side Socket for Sending Data
sSock = socket(AF_INET, SOCK_STREAM) sSock.connect((serverHost, serverPort)) sSock.send(item) data = sSock.recv(1024)
The socket module is also used to create a client-side socket that talks to the server-side socket discussed in the previous phrase.
The first step in implementing a client-side socket interface is to create the client socket by calling socket(family, type [, proto]), which creates and returns a new socket. family refers to the address family listed previously in Table 7.1, type refers to the socket types listed previously in Table 7.2, and proto refers to the protocol number, which is typically omitted except when working with raw sockets.
Once the client-side socket has been created, it can connect to the server socket using the connect(address) method, where address refers to a tuple in the form of (hostname, port).
After the client-side socket has connected to the server-side socket, data can be sent to the server using the send(string [,flags]) method. The response from the server is received from the connection using the recv(buffsize [,flags]) method.
import sys from socket import * serverHost = 'localhost' serverPort = 50008 message = ['Client Message1', 'Client Message2'] if len(sys.argv) > 1: serverHost = sys.argv #Create a socket sSock = socket(AF_INET, SOCK_STREAM) #Connect to server sSock.connect((serverHost, serverPort)) #Send messages for item in message: sSock.send(item) data = sSock.recv(1024) print 'Client received: ', 'data' sSock.close()
Client received: 'Processed Message1' Client received: 'Processed Message2'
Output from client_socket.py code