Socket
An interface between the application layer and the TCP,UCP protocol, the user only needs to operate the interface, and the complex data organization work is done internally by itself.
Socket (socket) for TCP protocol:
Service side
ImportSocketsk= Socket.socket ()#Create a Socket objectSk.bind (('127.0.0.1', 8080))#bind the IP address and port toSk.listen ()#MonitorConn, Address= Sk.accept ()#Create a connection whileTrue:ret= CONN.RECV (1024)#Receive data requires a specified number of bytes received ifret = = b'Bye': Conn.send (ret) Break Print(Ret.decode ('Utf-8') Info= Input ('>>>'). Encode ('Utf-8') Conn.send (info)#the sending data must be of type bytesConn.close ()#Close ConnectionSk.close ()#Close Socket
Client
ImportSocketsk= Socket.socket ()#Creating SocketsSk.connect (('127.0.0.1', 8080))#connecting to the service side whileTrue:info= Input ('>>>'). Encode ('Utf-8') Sk.send (info)#Send DataRET = SK.RECV (1024)#Receive Data ifret = = b'Bye': Break Print(Ret.decode ('Utf-8') ) Sk.close ()#Close Socket
Scoket (socket) for UDP protocol:
Service side
ImportSocketsk= Socket.socket (type=socket. SOCK_DGRAM)#Create a UCP socket objectSk.bind (('127.0.0.1', 8080))#binding IP and Portsmsg, Address= Sk.recvfrom (1024)#The UCP waiting to receive data must first receive dataPrint(Msg.decode ('Utf-8')) Sk.sendto (b'Hello', address)#send data to carry the address where the data is sentsk.close ()
Client
ImportSocketsk= Socket.socket (type=socket. SOCK_DGRAM)#Create a UCP socket objectIp_port = ('127.0.0.1', 8080)#specifying server-side IP and PortsSk.sendto (b'Hi', Ip_port)#send data to the specified service sideMSG, address = Sk.recvfrom (1024)#receive the returned dataPrint(Msg.decode ('Utf-8') ) Sk.close ()
Python Network programming socket