Based sockets (communication cycle) communication protocol tcp

Let the client and server can communicate with each other

from socket import *

client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))

# 通信循环
while True:
    msg=input('>>: ').strip()
    client.send(msg.encode('utf-8'))
    data=client.recv(1024)
    print(data)

client.close()
Client
# Server must meet at least three things: 
# 1 binds a fixed ip and Port 
# 2. external services has been stable operation 
# 3 is capable of supporting concurrent 
from socket Import * 

Server = socket (AF_INET, SOCK_STREAM) 
Server. the bind (( ' 127.0.0.1 ' , 8080 )) 
server.listen ( . 5)   # limit requests 

Conn, client_addr = server.accept () 

# communications cycle 
the while True: 
    data = conn.recv (1024) # accept data maximum limit 
    conn.send (data.upper ()) 

conn.Close () 
server.close ()
Server

There is a problem above, after the client is shut down, the server also followed close

Revision

from socket import *

client = socket(AF_INET, SOCK_STREAM)
client.connect(('127.0.0.1', 8080))

# 通信循环
while True:
    msg=input('>>: ').strip()
    client.send(msg.encode('utf-8'))
    data=client.recv(1024)
    print(data)

client.close()
Client
# Server must meet at least three things: 
# 1 binds a fixed ip and Port 
# 2. external services has been stable operation 
# 3 is capable of supporting concurrent 
from socket Import * 

Server = socket (AF_INET, SOCK_STREAM) 
Server. the bind (( ' 127.0.0.1 ' , 8080 )) 
server.listen ( . 5 ) 

Conn, client_addr = server.accept ()
 Print (client_addr) 

# communications cycle 
the while True:
     the try : 
        Data = conn.recv (1024 )
         IF len ( Data) == 0: BREAK # For linux system 
        Print ( ' -> receiving the client message: ' , Data) 
        conn.send (data.upper ()) 
    the except ConnectionResetError:
         BREAK 

conn.Close () 
server.close ()
Server

 

Guess you like

Origin www.cnblogs.com/zhouhao123/p/11267580.html