只有在服务器执行循环时,套接字客户端才从服务器接收消息

2024-04-20 00:18:56 发布

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

我试图让服务器(用Python编写)和客户机(用Java编写)进行通信。服务器代码如下:

import socket               # Import socket module
connection=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.bind(('',12800))
connection.listen(5)

connection_with_client, info_connection = connection.accept()

msg=b""
while(msg!=b"stop"):
    print("Entering loop")
    msg = connection_with_client.recv(1024)
    connection_with_client.send(b"This is a message")
    print("Sent")

connection_with_client.close()
connection.close()

客户端代码为:

try {
        socket = new Socket(InetAddress.getLocalHost(),12800); 

        PrintWriter out = new PrintWriter(socket.getOutputStream());
        out.print("stop");
        out.flush();
        System.out.println("Sent");
        in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
        String message_from_server = in.readLine();
        System.out.println("Received message : " + message_from_server);
        socket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {               
            e.printStackTrace();
    }

奇怪的是:当客户端发送消息“stop”时,一切正常,来自服务器的消息被客户端接收。现在,当客户机发送除“stop”之外的另一条消息时,服务器会告诉它已经发送了该消息,并再次进入循环,但是客户机从未接收到该消息,并且在最后一次发送时被卡住in.readLine文件()说明。你知道吗

我真的不明白为什么循环中的第一段在两种情况下应该有相同的效果。。。欢迎任何帮助!你知道吗


Tags: 服务器client消息客户端messagenewclose客户机
1条回答
网友
1楼 · 发布于 2024-04-20 00:18:56

在客户端,您正在使用readLine。很明显,它读取行,但是它如何检测行的结束位置?答案是: 服务器应该在发送给客户机的所有消息后面附加行结束符。你知道吗

试着在你的操作系统上附加b'\r\n'或者其他任何行尾。只要在客户端调用readLine,就应该附加客户端的行尾,而不是服务器操作系统。你知道吗

对于Windows,它是b'\r\n'

对于Linux b'\n'

相关问题 更多 >