gpt4 book ai didi

java - 服务器(Python)-使用套接字的客户端(Java)通信

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:42:15 24 4
gpt4 key购买 nike

我尝试从服务器向客户端发送一条消息,在客户端收到消息后,它向服务器发回一条消息,依此类推。问题是在 python 中接收消息。循环卡在那里。

import socket

HOST = "localhost"
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket created')

try:
s.bind((HOST, PORT))
except socket.error as err:
print('Bind failed. Error Code : ' .format(err))
s.listen(10)
print("Socket Listening")
conn, addr = s.accept()
while(True):
conn.send(bytes("Message"+"\r\n",'UTF-8'))
print("Message sent")
data = conn.recv(1024)
print(data.decode(encoding='UTF-8'))

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class Main {
static Thread sent;
static Thread receive;
static Socket socket;

public static void main(String args[]){
try {
socket = new Socket("localhost",9999);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
sent = new Thread(new Runnable() {

@Override
public void run() {
try {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while(true){
System.out.println("Trying to read...");
String in = stdIn.readLine();
System.out.println(in);
out.print("Try"+"\r\n");
System.out.println("Message sent");
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
});
sent.start();
try {
sent.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

最佳答案

Python 代码很好。问题是在 Java 代码中调用 out.print 不一定会导致您的消息立即通过套接字发送。添加

out.flush();

紧接着

out.print("Try"+"\r\n");

强制通过套接字发送消息。 (flush 通过流“刷新”任何尚未发送的数据。)然后 Python 应该能够正确接收它。

关于java - 服务器(Python)-使用套接字的客户端(Java)通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31983000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com