The socket module included with Python provides a generic interface to a variety of low-level socket programming. This phrase discusses how to implement a low-level socket server using the socket module. The first step in implementing a server-side socket interface is to create the server socket by calling -socket(family, type [, proto]), which creates and returns a new socket. family refers to the address family listed in Table 7.1, type refers to the socket types listed in Table 7.2, and proto refers to the protocol number, which is typically omitted except when working with raw sockets.
Once the socket has been created, it must be bound to an address and port using the bind(address) method, where address refers to a tuple in the form of (hostname, port). If the hostname is an empty string, the server will allow connections on any available Internet interface on the system. Note You can specify <broadcast> as the hostname to use the socket to send broadcast messages. After the socket has been bound to an interface, it can be activated by invoking the listen(backlog) method, where backlog is an integer that indicates how many pending connections the system should queue before rejecting new ones. Once the socket is active, implement a while loop to wait for client connections using the accept() method. Once a client connection has been accepted, data can be read from the connection using the recv(buffsize [,flags]) method. The send(string [,flags]) method is used to write a response back to the client. from socket import * serverHost = '' # listen on all interfaces serverPort = 50007 #Open socket to listen on sSock = socket(AF_INET, SOCK_STREAM) sSock.bind((serverHost, serverPort)) sSock.listen(3) #Handle connections while 1: #Accept a connection conn, addr = sSock.accept() print 'Client Connection: ', addr while 1: #Receive data data = conn.recv(1024) if not data: break print 'Server Received: ', data newData = data.replace('Client', 'Processed') #Send response conn.send(newData) #Close Connection conn.close() server_socket.py Client Connection: ('137.65.77.24', 1678) Server Received: Client Message1 Server Received: Client Message2 Output from server_socket.py code |