Socket-Socket related issues in Python3

Source: Internet
Author: User
This article mainly introduced the detailed PYTHON3 socket socket The coding problem solves, has the certain reference value, the interest small partner may refer to

First, TCP

1. TCP Server creation

 #创建服务器from socket import *from time import ctime #导入ctimeHOST = ' #任意主机PORT = 21567 #随机提供个端口号B Ufsiz = 1024 # The buffer size is set to 1KB, you can change this capacity according to network performance and program needs addr = (HOST, PORT) Tcpsersock = socket (af_inet, SOCK_STREAM) #分配了 TCP Server Set The socket Tcpsersock.bind (ADDR) #绑定到服务器地址以及开启 a call to the TCP listener. Tcpsersock.listen (5) The parameter of the #listen () method is that the maximum number of incoming connection requests "" After the connection has been forwarded or rejected, once in the infinite loop of the server, we are (passively) waiting 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. "" "While True:print (" Waiting for Connection ") tcpclisock, addr = Tcpsersock.accept () # Receives the client connection, returns the client and address print (" ... conn Ected from: ", addr) while true:data = Tcpclisock.recv (Bufsiz). Decode () #对话 (receive/Send) receive client's data if not data:b Reak tcpclisock.send (' Service: ' +ctime () + '--' +data '). Encode ()) #发送时间戳 and data information to the client Tcpclisock.close () Tcpsersock.close () 

2. TCP Client Creation


From socket import *host = ' localhost ' port = 21567      #端口号 port should be identical to the one you set for the server (otherwise, communication will not be possible) Bufsiz = 1024ADDR = (HOST, POR T) Tcpclisock = socket (af_inet, sock_stream)  #分配 TCP Client Socket Tcpclisock.connect (ADDR)  #主动连接  "" " We must decode the string from the server side (with the help of Distutils.log.warn () "" and True:  data = input (">")  if not data:   #用户如果没有输入, then terminate    break  Tcpclisock.send (Data.encode ())   #发送客户端的data给服务器  data = Tcpclisock.recv (Bufsiz). Decode () # The data if not data of the receiving server  :  The call to the #或者服务器终止且对 recv () method fails the 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


#这个脚本创建一个 the UDP client, which prompts the user to enter messages sent to the server and receives messages with timestamp prefixes from the server, and then displays them to the user. From socket import *host = ' localhost ' port = 21567      #端口号 port should be identical to the one you set for the server (otherwise, communication will not be possible) Bufsiz = 1024ADDR = (HOST, POR T) 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 same is true, in 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.

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.