

')Else: Chatwith=Clients Chatwith=SockElse: nd (' The user%sis not exist ' %DataElse:ifChatwith.has_key (sock): nd (' %s: (%s) ' %(CTime (), User,data))Else: nd (' Nobody is chating with you. ' %Data nd (data)delChatwith]delChatwithdelClients Sock.close () Break elifRe.match (' ^to.+ ', data) is not None: Data=dataifClients.has_key (data):ifData=User:nd (' please don\ 'T try to talk with yourself. PY fromSocketImport * fromTimeImportCTimeImportThreadingImportReHOST= "'PORT= 9999Bufsiz= 1024x768ADDR=(Host,port) Tcpsersock=Socket (Af_inet,sock_stream) tcpsersock.bind (ADDR) Tcpsersock.listen (5) clients=# Clients dictionary that records the corresponding relationship between the user name and the socket of the connected client# Chatwith The correspondence between the two sides of the communication is recorded in the dictionary# messagetransform () processing the text sent after the client determines the user name# There are only four types of text:# None# Quit# To:someone# Other textdefMessagetransform (Sock,user): while True: Data=SOCK.RECV (Bufsiz)if notDataifChatwith.has_key (sock): nd (data)delChatwith]delChatwithdelClients Sock.close () Break ifData=' Quit ': nd (data)ifChatwith.has_key (sock): Data= '%s.

Maybe the one talked with are talking with someone else " After entering the user name, the client needs to determine a chat user, client input, and To:user if the client sends other text, it will receive a prompt from the server: "Nobody is chatting with you.

A client runs, the connection succeeds after entering the user name, the server will save the user name in a dictionary, the corresponding relationship of the dictionary is username -> socket.This version is very primitive, it only realizes the simplest chat, there are a lot of places to pay attention to.

Multi-user full-duplex Chat Humble editionĪ simple implementation of communication between two clients, the client sends a message, first received by the server, and then forwarded to another client.
