Nothing special, the C/s frame of the online rotten Street. (Based on Windows 7 + Python 3.4)
In order to achieve Chinese chat, I added a little change:
Msg.encode ('utf-8'# msg is the input (and will be sent) information data.decode (' utf-8'# data for the information received
The reason for this is that the sendto function can only send ASCII characters and does not support sending Chinese (in Python3, Chinese default is Unicode encoding ).
So, the message is encoded before it is sent out and decoded after the message is received
The complete two files are as follows:
#udp-server.py" "Server" " fromSocketImport*Host="' #Server AddressPort = 12345#Server PortBufsiz = 2048#Cache SizeAdds = (host, port)#address + PortUdpsersock= Socket (af_inet, SOCK_DGRAM)#Create a socket type for UDP. Udpsersock.bind (adds)#binding to addresses and ports whiletrue:msg= Input ('server says:')#input Datadata, ADDC =Udpsersock.recvfrom (Bufsiz) udpsersock.sendto (Msg.encode ('Utf-8'), ADDC)if notData Break Print('The client answers:', Data.decode ('Utf-8') ) Udpsersock.close ()
#udp-client.py" "Client" " fromSocketImport*Host='localhost' #Local server addressPort = 12345#client port (ensure that the port is consistent with the serverBufsiz = 2048#Cache SizeADDC = (host, port)#address + PortUdpclisock= Socket (af_inet, SOCK_DGRAM)#Create a socket type for UDP. whiletrue:msg= Input ('The client says:')#input DataUdpclisock.sendto (Msg.encode ('Utf-8'), ADDC) data, adds=Udpclisock.recvfrom (Bufsiz)if notData Break Print('Server Answer:', Data.decode ('Utf-8') ) Udpclisock.close ()
Run results
(Spit slot: Python input How to press ENTER is useless, only CTRL + D + Enter.) Heroes Save me!!! )
Python+soket implementation of UDP protocol client/server Chinese chat program