Examples of python Tcp Protocol Sending and Receiving Information

  • 2021-07-24 11:13:06
  • OfStack

Two files need to be created, one as the client and one as the server

File 1 is the client client and File 2 is the server server

Document 1


# client  Client 
# TCP You must establish a connection 
import socket  # Import module 
# SOCK_STREAM---TCP Protocol mode 
# AF_INET---- Mine is ipv4 Address 
#1, Create socket Object: Specifies the transport protocol 
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#2 Establish a connection and send a connection request  ip Address and port number 
s.connect(('127.0.0.1',8000))
s.send(" How do you do ".encode()) # You can only send byte streams. You need to use encode Transcode string into bytes, otherwise you can't send files 

Document 2:


# Server side server
 
import socket
#1 Create socket Object 
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Must be maintained with the client 1 To 
#2 You need to bind yourself 1 A ip Address and port number 
s.bind(('127.0.0.1',8000))
#3 The server always pays attention to whether there is a client request when listening to the operation 
s.listen(3)  # You can listen at the same time 3 A, but there is only one here 1 Client requests because multithreading is not written 
#4, Agree to the connection request 
s1,addr=s.accept()  #s Is server-side socket Object s1 Is the accessed client socket Object 
print(addr)
#5 , revice Receive data 
data=s1.recv(1024) # Setting 1 Secondary receivable 1024 Byte size 
print(data.decode())# The byte stream passed in requires the decode() Decoding 

When running files, run the file 2 server first, and then run the file 1 client


Related articles: