Python network programming uses Python for TCP, UDP socket programming

Source: Internet
Author: User

Prior to implementing the Java version of the TCP and UDP socket programming example, so decided to combine Python learning to do a python version of the socket programming experiment.

The process is as follows:

1. A client reads a line of characters from its standard input (keyboard) and sends the line to the server through its sockets.

2. The server reads a line of characters from its connection socket.

3. The server converts the line character to uppercase.

4. The server sends the modified string (line) back to the client by connecting the socket.

5. The client reads the modified line from its socket and prints the row on its standard output (monitor).

"TCP" server-side code:

ImportSocketImport TimeImportthreadings= Socket.socket (socket.af_inet, socket. SOCK_STREAM)#Create sockets (Af_inet:ipv4, Af_inet6:ipv6) (Sock_stream: Stream-oriented TCP protocol)S.bind (('127.0.0.1', 10021))#bind the machine IP and any port (>1024)S.listen (1)#listening, the maximum number of waiting connections is 1Print('Server is running ...')                                                         defTCP (sock, addr):#TCP server-side processing logic        Print('Accept New Connection from%s:%s.'%ADDR)#accept a new connection request     whileTrue:data= SOCK.RECV (1024)#accept its dataTime.sleep (1)#Delay        if  notDataorData.decode () = ='quit':#If the data is empty or ' quit ', exit             Breaksock.send (Data.decode ('Utf-8'). Upper (). Encode ())#Send to uppercase data, need to decode first, and then press UTF-8 encoding, encode () is actually encode (' utf-8 ')sock.close ()#Close Connection    Print('Connection from%s:%s closed.'%addr) whileTrue:sock, addr= S.accept ()#接收一个新连接TCP (sock, addr) #处理连接

"TCP" Client code:

ImportSockets= Socket.socket (socket.af_inet, socket. SOCK_STREAM)#Create a socketS.connect (('127.0.0.1', 10021))#Establish a connection whileTrue:#Accept Multiple DataData= Input ('Please enter the data you want to send:')#Receive Data    ifdata = ='quit':#if ' Quit ', exit         BreakS.send (Data.encode ())#Send encoded Data    Print(S.recv (1024x768). Decode ('Utf-8'))#print the received uppercase dataS.send (b'quit')#Discard Connections.close ()#Close Socket

Operation Result:

The UDP protocol does not need to establish a connection in advance to send data directly to each other.

"UDP" server-side code:

ImportSockets= Socket.socket (socket.af_inet, socket. SOCK_DGRAM)#Create a Socket,sock_dgram to represent the UDPS.bind (('127.0.0.1', 10021))#bind IP address and portPrint('Bound UDP on 10021 ...') whileTrue:data, addr= S.recvfrom (1024)#get the address and port of the data and client, and receive the maximum 1024 bytes at a time    Print('Received from%s:%s.'%addr) s.sendto (Data.decode ('Utf-8'). Upper (). Encode (), addr)#turn data into uppercase and send back to the client#do not close the socket

"UDP" Client code:

ImportSockets=Socket.socket (socket.af_inet, socket. SOCK_DGRAM) Addr= ('127.0.0.1', 10021)#server-side address whileTrue:data= Input ('Please enter the data to be processed:')#Get the data    if  notDataordata = ='quit':         Breaks.sendto (Data.encode (), addr)#Send to service sideRecvData, addr = S.recvfrom (1024)#receiving data from the server side    Print(Recvdata.decode ('Utf-8'))#Decoding Printings.close ()#Close Socket

Operation Result:

Python network programming uses Python for TCP, UDP socket programming

Related Article

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.