为什么我的True循环没有破坏?

时间:2018-02-12 20:37:29

标签: python sockets

我试图建立一个简单的聊天室,但从基础开始。我有一个服务器向客户端发送字符串,但是,我的while循环不会中断。

服务器

import socket

HOST = ''                 # Symbolic name meaning the local host
PORT = 50023  # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
conn.send("hello client")
conn.send("\nhow are you")
conn.send("stop")

客户端

import socket

HOST = 'localhost'    # The remote host
PORT = 50023       # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

while True:
    data = s.recv(1024)
    if data == "stop": 
        break
    print(data)
print("we got here")

我想指出我也尝试过

if not data:
   break

那不起作用

2 个答案:

答案 0 :(得分:5)

您的服务器正在发送:

hello client\nhow are youstop

但是您的客户正在测试

 stop

"hello client\nhow are youstop" != "stop"起,您不太可能点击break声明。

意识到TCP提供了可靠的字节流;只要每个字节按正确的顺序到达目的地,就可以完成TCP的工作。没有消息边界,只有字节边界。一方的.recv()无需以任何方式与其他方.send()对齐。

如果您想要保留邮件边界的服务,可以尝试使用UDP。或者,您可以在TCP之上实现自己的消息框架(例如换行符或类型长度值元组)。

答案 1 :(得分:0)

您的代码中的细微变化使您可以在简单的聊天中继续进行。

首先,不要发送字符串。使用二进制文件在服务器和客户端之间发送消息。

例如,服务器的代码为:

import socket

HOST = ''                 # Symbolic name meaning the local host
PORT = 50023  # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connected by', addr)
conn.send(b"hello client")
conn.send(b"\nhow are you")
conn.send(b"stop")

注意服务器现在正在发送二进制文件(在字符串之前使用b来设置二进制数据)。

在客户端,您发送的所有数据都像数据流一样被接收。要打破while循环,您需要检查流的结尾,如下面的代码所示:

import socket

HOST = 'localhost'    # The remote host
PORT = 50023       # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

while True:
    data = s.recv(1024)
    if data.endswith(b'stop'): 
        break
    print(data)
print(b"we got here")

我希望它对你有用!

相关问题