socket () module function usage
ImportSocketsocket.socket (socket_family,socket_type,protocal=0) socket_family can be Af_unix or af_inet. Socket_type can be sock_stream or sock_dgram. Protocol is generally not filled, the default value is 0. Get TCP/IP Socket tcpsock=Socket.socket (socket.af_inet, socket. SOCK_STREAM) Get UDP/IP Socket udpsock=Socket.socket (socket.af_inet, socket. SOCK_DGRAM) Because there are too many properties in the socket module. We made an exceptional use of it here.'From module Import *'Statement. Use'From socket Import *', we took all the attributes from the socket module into our namespace, which greatly shortened our code. such as Tcpsock= Socket (af_inet, SOCK_STREAM)
The socket communication process is similar to the call process, so we use the phone as an example to implement a low version of socket communication
Service side:
ImportSocket#1. Buy Mobile phonePhone=socket.socket (Socket.af_inet,socket. SOCK_STREAM)#TCP is called a streaming protocol, and UDP is called Datagram Protocol Sock_dgram#print (phone)#2. Insert/bind Mobile card#phone.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1)Phone.bind (('127.0.0.1', 8082))#3. BootPhone.listen (5)#semi-connection pool, limit the number of requests#4, waiting for the telephone connectionPrint('start ....') conn,client_addr=phone.accept ()#(three-time handshake established two-way connection (client IP, port))#PRINT (conn)Print(CLIENT_ADDR)#5. Communication: receiving \ Sending messages whileTrue:#Communication CycleDATA=CONN.RECV (1024)#maximum number of bytes received Print('data from the client', data) Conn.send (Data.upper ())#6. Hang up the phone connectionconn.close ()#7. Shut down the machinePhone.close ()
Client:
ImportSocket#1. Buy Mobile phonePhone=Socket.socket (Socket.af_inet,socket. SOCK_STREAM)Print(phone)#2. Dial phonePhone.connect (('192.168.13.45', 8080))#specifying server-side IP and Ports#3, communication: send \ Receive Messages whiletrue:msg=input ('>>>:'). Strip () Phone.send (Msg.encode ('Utf-8')) #phone.send (bytes (' Hello ', encoding= ' Utf-8 '))DATA=PHONE.RECV (1024) Print(data)#4. ClosePhone.close ()
The socket in Python