One, code example
Service side:
1 ImportSocket2 3 4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5Phone.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)6Phone.bind (('127.0.0.1', 8080))#0-65535:0-1024 for operating system use7Phone.listen (5)8 9 Print('starting .....')Ten whileTrue:#Link Loops Oneconn, client_addr =phone.accept () A Print(CLIENT_ADDR) - - whileTrue:#Communication Cycle the Try: -data = CONN.RECV (1024) - if notData#for Linux operating systems - Break + Print('client-side data', data) - + Conn.send (Data.upper ()) A exceptConnectionreseterror:#for Windows operating systems at Break - - conn.close () - -Phone.close ()
Client 1
1 ImportSocket2 3 #1. Buy Mobile phone4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5 #print (phone)6 7 #2. Dialing8Phone.connect (('127.0.0.1', 8080))9 Ten #3. Send and receive Messages One whileTrue: Amsg = input ('>>:'). Strip () - if notmsg: - Continue thePhone.send (Msg.encode ('Utf-8')) -data = PHONE.RECV (1024) - Print(data) - + #4. Close -Phone.close ()
Client 2
1 ImportSocket2 3 #1. Buy Mobile phone4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5 #print (phone)6 7 #2. Dialing8Phone.connect (('127.0.0.1', 8080))9 Ten #3. Send and receive Messages One whileTrue: Amsg = input ('>>:'). Strip () - if notmsg: - Continue thePhone.send (Msg.encode ('Utf-8')) -data = PHONE.RECV (1024) - Print(data) - + #4. Close -Phone.close ()
After the link loop, the server can provide services to client 1 and client 2 in turn, but can serve only one client and cannot provide services in parallel
python--Network Programming-----Socket Programming Example--call--plus link loop