Solve the encoding problem of socket in python3, python3socket

Source: Internet
Author: User

Solve the encoding problem of socket in python3, python3socket

I. TCP

1. Create a tcp Server

# Create a server from socket import * from time import ctime # import ctimeHOST = ''# Any host PORT = 21567 # randomly provide a PORT number BUFSIZ = 1024 # Set the buffer size to 1KB, you can change the capacity ADDR = (HOST, PORT) tcpSerSock = socket (AF_INET, SOCK_STREAM) According to network performance and program needs # allocate TCP server socket tcpSerSock. bind (ADDR) # bind to the server address and enable TCP listener calls. TcpSerSock. the listen (5) # listen () method parameter is the maximum number of incoming connection requests before the connection is transferred or denied. "once it enters the infinite loop of the server, we will (passively) Wait for the client connection. When a connection request appears, we enter the dialog loop, in which we wait for the message sent by the client. If the message is blank, it means that the client has exited, so now we will jump out of the dialog loop, close the current client connection, and wait for another client connection. If a message sent by the client is obtained, it is formatted and the same data is returned, but the prefix of the current timestamp is added to the message. The last line will never be executed. It is only used to remind readers. if you write a handler to consider a more elegant exit method, as discussed earlier, you should call the close () method. "While True: print (" waiting for connection ") tcpCliSock, addr = tcpSerSock. accept () # receive client connection, return client and address print ("... connected from: ", addr) while True: data = tcpCliSock. recv (BUFSIZ ). decode () # receive/send a dialog) receive data from the client if not data: break tcpCliSock. send ('service: '+ ctime () +' -- '+ data ). encode () # Send the timestamp and data information to the client tcpCliSock. close () tcpSerSock. close ()

2. Create a tcp client

From socket import * HOST = 'localhost' PORT = 21567 # the PORT number must be exactly the same as the one you set for the server (otherwise, communication will fail) BUFSIZ = 1024 ADDR = (HOST, PORT) tcpCliSock = socket (AF_INET, SOCK_STREAM) # allocate TCP client socket tcpCliSock. connect (ADDR) # actively connect "". We must decode the string from the server (by using distutils. log. warn () "" while True: data = input (">") if not data: # if the user does not enter data, terminate break tcpCliSock. send (data. encode () # Send client data to server data = tcpCliSock. recv (BUFSIZ ). decode () # receive the server's data if not data: # Or the server terminates and fails to call the recv () method break print ('Return: % s' % data) tcpCliSock. close ()

Ii. UDP

1. Create a UDP Server

"This script creates a UDP server that accepts messages sent from the client and returns the message with the timestamp prefix to the client. "From socket import * from time import ctimeHOST =" "PORT = 21567 BUFSIZ = 1024 ADDR = (HOST, PORT) udpServer = socket (AF_INET, SOCK_DGRAM) udpServer. bind (ADDR) while True: print ("waiting for masssage") data, addr = udpServer. recvfrom (BUFSIZ) # receive data = data. decode () udpServer. sendto (ctime () + "--" + data ). encode (), addr) print ("received from and returned to", addr) udpServer. close ()

2. Create a UDP client

# This script creates a UDP client that prompts the user to enter the messages sent to the server, receive the messages with the timestamp prefix on the server, and then display them to the user. From socket import * HOST = 'localhost' PORT = 21567 # the PORT number must be exactly the same as the one you set for the server (otherwise, communication will fail) BUFSIZ = 1024 ADDR = (HOST, PORT) udpCS = socket (AF_INET, SOCK_DGRAM) while True: data = input (">") if not data: break udpCS. sendto (data. encode (), ADDR) data, ADDR = udpCS. recvfrom (BUFSIZ) if not data: break print (data) udpCS. close ()

In fact, the truth is almost the same. In python3, the content transmitted using socket is transmitted in byte format. At this time, when sending (send/sendto), encode is required, and when receiving (recv), decode is required. As long as you master this key point, it is very easy to solve this problem.

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.