Python+soket implementation of UDP protocol client/server Chinese chat program

Source: Internet
Author: User
Tags server port

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.