Solution of socket socket encoding problem in Python3

Source: Internet
Author: User
Tags terminates

First, TCP

1. TCP Server creation

#Creating a server fromSocketImport* fromTimeImportCTime#Import CTimeHOST="'       #any hostPORT = 21567#provide a random port numberBufsiz = 1024#The buffer size is set to 1KB, which can be changed depending on network performance and program needsADDR =(HOST, PORT) Tcpsersock= Socket (af_inet, SOCK_STREAM)#TCP server sockets are assignedTcpsersock.bind (ADDR)#A call to bind to the server address and turn on the TCP listener. Tcpsersock.listen (5)#the parameter of the Listen () method is the maximum number of incoming connection requests before the connection is forwarded or rejected"""Once inside the infinite loop of the server, we wait (passively) for the client to connect. When a connection request appears, we enter the conversation loop where we wait for the message sent by the client. If the message is blank, this means that the client has exited, so at this point we will jump out of the conversation loop, close the current client connection, and wait for another client to connect. If you do get a message sent by the client, it is formatted and returns the same data, but the current timestamp prefix is added to the data. The last line is never executed, it is just to remind the reader that if a handler is written to consider a more graceful exit method, as discussed earlier, the close () method should be called. """ whileTrue:Print("Waiting for connection") Tcpclisock, addr= Tcpsersock.accept ()#receiving client connections, returning clients and addresses    Print("... connected from:", addr) whileTrue:data= Tcpclisock.recv (Bufsiz). Decode ()#dialog (receive/send) the data of the receiving client        if  notData: BreakTcpclisock.send (('Service:'+ctime () +'--'+data). Encode ())#send timestamp and data information to the clienttcpclisock.close () tcpsersock.close ( )

2. TCP Client Creation

 fromSocketImport*HOST='localhost'PORT= 21567#Port number port should be exactly the same as the one you set for the server (otherwise, communication will not be possible)Bufsiz = 1024ADDR=(HOST, PORT) Tcpclisock= Socket (af_inet, SOCK_STREAM)#assigning TCP client socketsTcpclisock.connect (ADDR)#Active Connection"""we must decode the string from the server side (with the help of the Distutils.log.warn ()""" whileTrue:data= Input (">")    if  notData#If the user does not have input, it terminates         BreakTcpclisock.send (Data.encode ())#send the client's data to the serverdata = Tcpclisock.recv (Bufsiz). Decode ()#data from the receiving server    if  notData#or the server terminates and the call to the Recv () method fails         Break    Print('return:%s'%data) Tcpclisock.close ()

Second, UDP

1. UDP Server creation

"" "    this script creates a UDP server that accepts messages from the client and returns the timestamp prefixed message to the client. "" "from socket import *from time Import ctimehost =" "PORT = 21567BUFSIZ = 1024ADDR = (HOST, PORT) Udpserver = socket (af_in ET, Sock_dgram) Udpserver.bind (ADDR) while True:    print ("Waiting for Masssage")    data,addr = Udpserver.recvfrom ( BUFSIZ) #接收    data = Data.decode ()    udpserver.sendto ((CTime () + "--" + data). Encode (), addr)    print ("Received From  and returned to ", addr) Udpserver.close ()

2. UDP Client Creation

#This script creates a UDP client that prompts the user to enter a message sent to the server and receives a message with a timestamp prefix from the server, and then displays them to the user.  fromSocketImport*HOST='localhost'PORT= 21567#Port number port should be exactly the same as the one you set for the server (otherwise, communication will not be possible)Bufsiz = 1024ADDR=(HOST, PORT) udpcs=socket (af_inet, SOCK_DGRAM) whileTrue:data= Input (">")    if  notData: Breakudpcs.sendto (Data.encode (), ADDR) data,addr=Udpcs.recvfrom (Bufsiz)if  notData: Break    Print(data) udpcs.close ()

In fact, the same reason, in the Python3, the use of socket transmission of the content is transmitted in byte form, when the transmission (send/sendto) need to encode, receive (recv) need decode. It is easy to deal with this problem as long as you master the point.

Solution of socket socket encoding problem in Python3

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.