First, the service side
1 ImportSocket2 3 4Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)5Phone.bind (('127.0.0.1', 8080))#0-65535:0-1024 for operating system use6Phone.listen (5)7 8 Print('starting .....')9conn, client_addr =phone.accept ()Ten Print(CLIENT_ADDR) One A whileTrue:#Communication Cycle -data = CONN.RECV (1024) - Print('client-side data', data) the - Conn.send (Data.upper ()) - - conn.close () +Phone.close ()
Second, the client
1 ImportSocket2 3 4 #1. Buy Mobile phone5Phone =Socket.socket (socket.af_inet, socket. SOCK_STREAM)6 #print (phone)7 8 #2. Dialing9Phone.connect (('127.0.0.1', 8080))Ten One #3. Send and receive Messages A whileTrue: -msg = input ('>>:'). Strip () -Phone.send (Msg.encode ('Utf-8')) thedata = PHONE.RECV (1024) - Print(data) - - #4. Close +Phone.close ()
The client results are:
1 >>: He2 b'he'3 >>: asdf4 b'ASDF'5 >>:
The results of the service end are:
1 starting ..... 2 ('127.0.0.1', 64037)3 client data b'he' 4 client data b'asdf'
Third, there is time to run the service-side program, the display port usage error, you can use the following code to prevent this situation
1 phone.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)
Four, when the client input is empty (that is, direct carriage return), press ENTER, the client has been across there,
Cause Analysis:
The client sends the empty information needs to call the operating system interface, the client program in memory to send the information to copy to the operating system memory, if empty, the operating system memory does not receive data, it will not be sent to the server, so there is a client across the phenomenon
Workaround:
To modify the client code:
1 whileTrue:2msg = input ('>>:'). Strip ()3 if notmsg:4 Continue5Phone.send (Msg.encode ('Utf-8'))6data = PHONE.RECV (1024)7 Print(data)
V. If the client disconnects unexpectedly, the server will have a dead loop on the Linux system, and the server will make a direct error on the Windows system.
Workaround:
To modify the service-side code:
1 whileTrue:#Communication Cycle2 Try:3data = CONN.RECV (1024)4 if notData#for Linux operating systems5 Break6 Print('client-side data', data)7 8 Conn.send (Data.upper ())9 exceptConnectionreseterror:#for Windows operating systemsTen Break
python--Network Programming-----Socket Programming Example--call--plus communication loops