

The client has to actually listen for server message and user input at the same time. If the user types in a message then send it to the server.
MULTI CHAT CLIENT CODE
Now lets code the chat client that will connect to the above chat server. Print "Client (%s, %s) is offline" % addrĬhat server started on port 5000 Chat client # a "Connection reset by peer" exception will be thrownīroadcast_data(sock, "Client (%s, %s) is offline" % addr) #In Windows, sometimes when a TCP program closes abruptly, # Handle the case in which there is a new connection recieved through server_socketīroadcast_data(sockfd, " entered room\n" % addr) Print "Chat server started on port " + str(PORT) # Add server socket to the list of readable connections Server_tsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) Server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2 # List to keep track of socket descriptors #Function to broadcast chat messages to all connected clients
MULTI CHAT CLIENT FULL
Here is the full code of the chat client. Rest of the program is quite self explanatory. If the broadcast function fails to send message to any of the client, the client is assumed to be disconnected and the connection is closed and the socket is removed from the connection list. # broken socket connection may be, chat client pressed ctrl+c for example If socket != server_socket and socket != sock : #Do not send the message to master socket and the client who has send us the message The following function broadcasts the message to all chat clients. If any of the client socket is readable, the server would read the message, and broadcast it back to all clients except the one who send the message. So if the master socket is readable, the server would accept the new connection. When the select function returns, the read_sockets will be an array consisting of all socket descriptors that are readable. Read_sockets,write_sockets,error_sockets = lect(CONNECTION_LIST,) # Get the list sockets which are ready to be read through select If any of the client socket is readable then it means that one of the chat client has send a message. The select function monitors all the client sockets and the master socket for readable activity. The server handles multiple chat clients with select based multiplexing. You can change the port number if you want. The chat client must connect to this same port. It server opens up port 5000 to listen for incoming connections.

In our previous article on socket programming in python we learned about the basics of creating a socket server and client in python.
