套接字编程:客户端在向服务器发送3条消息后停止响应

2024-04-27 19:37:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我对socket编程非常陌生,我想知道为什么在我向服务器发送了3条消息之后客户端停止响应。基本上,我发送两次消息,服务器响应客户机。第三次,客户端只是无限运行,而服务器没有收到任何东西

这和超载有关吗?这是如何工作的,尤其是使用socket.listen()时

以下是代码供参考:

client.py

# Import socket module 
import socket                

# Create a socket object 
s = socket.socket()          

# Define the port on which you want to connect 
port = 12345                

# connect to the server on local computer 
s.connect(('127.0.0.1', port)) 

while True:

    msg = input("Enter your message: ")

    if msg != "quit":
        s.send((msg).encode())

    else:
        # close the connection 
        s.close()      

    # receive data from the server 
    new_msg = (s.recv(1024).decode())
    print ("[CLIENT]: ", new_msg) 

server.py

# first of all import the socket library 
import socket                

# next create a socket object 
s = socket.socket()          
print ("Socket successfully created")

# reserve a port on your computer in our 
# case it is 12345 but it can be anything 
port = 12345                

# Next bind to the port 
# we have not typed any ip in the ip field 
# instead we have inputted an empty string 
# this makes the server listen to requests  
# coming from other computers on the network 
s.bind(('', port))         
print ("socket binded to %s" %(port)) 


# a forever loop until we interrupt it or  
# an error occurs 
while True: 

    # put the socket into listening mode 
    s.listen(20)      
    print ("socket is listening")

    # Establish connection with client. 
    c, addr = s.accept()      
    print('Got connection from', addr) 

    msg = c.recv(1024).decode()

    if msg == "quit":
        # Close the connection with the client 
        c.close() 
    else:
        print ("[SERVER]: Recieved data: ", msg)

    print ("[SERVER]: sending", msg)

    c.send((msg).encode())

Tags: thetofromimportclientcloseserveron
1条回答
网友
1楼 · 发布于 2024-04-27 19:37:03

您仍然需要更好地了解侦听套接字的工作原理:

  • 它只听一次
  • 每个连接只接受一次
  • 它可以根据需要读取和发送任意数量的数据包,直到任意一方关闭连接
  • 在这一点上(对于单线程服务器),它准备接受一个新的连接

您的server.py应该是:

...
s.bind(('', port))         
print ("socket binded to %s" %(port)) 

# put the socket into listening mode 
s.listen(20)      
print ("socket is listening")

# a forever loop until we interrupt it or  
# an error occurs 
while True: 

    # Establish connection with client. 
    c, addr = s.accept()      
    print('Got connection from', addr) 

    while True:
        msg = c.recv(1024).decode()

        if len(msg) == 0:          # the client does not send anything but just closes its side


            # Close the connection with the client 
            c.close()
            print('Client disconnected')
            break
        else:
            print ("[SERVER]: Recieved data: ", msg)

        print ("[SERVER]: sending", msg)

        c.send((msg).encode())

客户端的一个小补丁:

    ...
    if msg != "quit":
        s.send((msg).encode())

    else:
        # close the connection 
        s.close()
        break           # break out of the loop after closing connection

但这并不是全部:TCP是一种流协议。在到达另一侧之前,您应该准备好将从一侧发送的数据包拆分或重新组装。唯一的保证是字节的到达顺序与发送顺序相同,但不一定在相同的数据包中

相关问题 更多 >