Once a socket has been bound to a port, the next step is to make it listen for incoming requests. To do this, the listen() method needs to be called on the socket object. The listen() method accepts the number of requests to be kept in queue as the argument. For example, to make a socket start listening with a queue of size 3, the statement will be server_socket.listen(3) Accepting the requests Once a request is received, it has to be accepted so that communication can start. To do so, one has to call the accept() method on the socket object. The accept() method doesn't have any arguments. It returns a tuple containing the address of the client and socket object through which further communication can be accomplished. So the statement to accept a connection is client_socket,address=server_socket.accept() Sending/receiving data The last step is sending and/or receiving data. If the server is on a normal PC, then sending and receiving can be done using the Python library. However, if the server is on a smart phone, for example, then the library required will be based on the OS of the smart phone. For a normal PC, one would have to call send() and recv() methods on the socket object returned by the accept() method. Both accept strings as arguments. For example, if the server wants to send a message, say, "hello", the code will be client_socket.send("Hello from server") That completes the server part. Next comes the client.
blog comments powered by Disqus |