Python can invoke the socket module for TCP/UDP processing. The socket can choose a different type, that is, a socket for UNIX threads and a processing interface that is provided to the upper level for the TCP/IP protocol. TCP/UDP is through the socket interface to establish the corresponding socket object, indicating that the interface parameter processing types have SOCK_DGRAM and sock_stream differences, UDP is connectionless, and TCP is connection-oriented, so in the processing of a slight difference, TCP processing requires the listen interface to listen for TCP handshake processes to occur. UDP Server and Client program sample service-side programs
#!/usr/bin/python3.6
Import Socket
buffer_size = 1024
target_addr = ' #表示为本地主机
target_port = 60000
TARGET = (target_addr,target_port)
#AF_INET表示为网络编程socket, SOCK_DGRAM Select UDP protocol mode
SS = Socket.socket ( Socket.af_inet,socket. SOCK_DGRAM)
ss.bind (TARGET) #绑定对应的IP地址及端口号 while
True:
DATA,ADDRRSV = Ss.recvfrom (buffer_size)
if Not data:
sys.exit (0)
else:
print (data)
Ss.close ()
Client programs
#!/usr/bin/python3.6
Import Socket
ss = Socket.socket (Socket.af_inet,socket. SOCK_DGRAM)
buffer_size = 1024
target_addr = ' IP address '
target_port = 60000
TARGET = (target_addr, Target_port) while
True:
AA = input (' > ') #输入相应数据
if not AA:
a break #需要为字节型数据, Send the data to the appropriate destination IP address and port number
ss.sendto (bytes (AA, ' Utf-8 '), target)
DATA,ADDRRSV = Ss.recvfrom (buffer_size)
if Not data:
break
Else:
print (data)
print (ADDRRSV)
ss.close ()
TCP server-side and client-side programs sample server-based programs
#!/usr/bin/python3.6
from socket import *
buffersize = 1024
#SOCK_STREAM选择为TCP协议
s = socket (af_inet, SOCK_STREAM) # Create TCP socket
s.bind (("", 60000)) # bind to Port 60000
S.listen () # Start listening while
1:
client,addr = s.accept () # Wait for a connection has blocking feature
print ("Got a connection from", addr)
client.send (b ' C Onnect successfully ')
AA = Client.recv (buffersize)
print (AA)
client.close ()
Client programs
#!/usr/bin/python3.6 from
socket import *
buffersize = 1024
SS = socket (af_inet,sock_stream) # Create TCP Socket
Ss.connect (("IP address", 60000) # Connect to the server
tmp = SS.RECV (buffersize) # Receive up to 1024 b Ytes
Print (TMP)
ss.send (b "Feedback")
Ss.close () # Close connection