The following code is used to illustrate the basics of the TCP protocol:
Server-side code block:
fromSocket Import * fromTime Import CTime" "Specifies the host address, the working port number, the length of the receive cache server-side host is empty, indicating that it can use any available address" "host="'PORT=21263Bufsiz=1024x768ADDR=(host,port) # Create sockets, BIND sockets to server addresses, turn on TCP snooping Tcpsvrsock=socket (af_inet,sock_stream) tcpsvrsock.bind (ADDR) Tcpsvrsock.listen (5) whileTrue:" "the connection to the receiving client is constantly waiting. We obtain the client's Tcpclisock and addr through the accept (), so that the client's transactions can be specifically handled by this tcpclisock (which distinguishes it from the other requesting clients)" "Tcpclisock,addr=tcpsvrsock.accept () print ('content from:', addr) # print ('Tcpclisock:', Tcpclisock) whileTrue:data=tcpclisock.recv (Bufsiz)ifNot data: Break# not empty to parse the message, add timestamp data=data.decode ('Utf-8') print (data) data1=input ('reply to client:') respmsg='[%s]%s'%(CTime (), data1) # has been re-encoded into ASCII bytes, sent back via send () to the client Tcpclisock.send (bytes (respmsg,'Utf-8')) Tcpclisock.close () tcpsvrsock.close ()
Client code block:
fromSocket Import *" "Specify the host address, the working port number, the length of the receive cache the host here is the address of the server, and since I am testing the communication locally, the address is set to 127.0.0.1(localhost). In the actual network communication, according to the specific circumstances of the corresponding modification. The port that the client fills in must correspond to the port that the server fills in to communicate properly. " "host='127.0.0.1'PORT=21263Bufsiz=1024x768ADDR=(Host,port) # Creates a socket, actively invokes and connects to the server via connect (). Tcpclisock=socket (af_inet,sock_stream) tcpclisock.connect (ADDR) whileTrue:data=input ('>>>') ifNot data: Breaktcpclisock.send (bytes (data,'Utf-8')) ifNot data: Break# The data returned by the receiving server Rscdata=tcpclisock.recv (bufsiz) print (Rscdata.decode ('Utf-8') ) Tcpclisock.close ()" "if we want to change the code to the corresponding IPv6 form, we just need to change the host to "::1sock_family changed to Af_inet6. " "
More detailed information can be found in: 79128137
For more port protocols see: Https://www.cnblogs.com/taoke2016/p/9047981.html
TCP Network Protocol communication principle (client and server side)