gpt4 book ai didi

java - 在后台接收消息

转载 作者:行者123 更新时间:2023-12-02 12:47:25 25 4
gpt4 key购买 nike

Java 客户端-服务器。需要在后台接收客户端的消息。我正在尝试在后台接收消息:

public Server() throws IOException {
try {
serverSocket=new ServerSocket(1234);
fromclient= serverSocket.accept();
System.out.println("Socket created");
} catch (IOException e) {
e.printStackTrace();
System.out.println("Socket not created");
}
try {
in = new BufferedReader(new
InputStreamReader(fromclient.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
out = new PrintWriter(fromclient.getOutputStream(),true);
String input,output;
}

背景部分:

 public void run(ServerSocket welcomeSocket) throws IOException {
Socket connectionSocket = welcomeSocket.
accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence =
clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}

并在客户端部分发送消息:

  Client client=new Client();
client.Connect();
client.sendToServer("text test");
Run run=new Run();

void run() throws IOException {
BufferedReader inFromUser =
new BufferedReader(
new InputStreamReader(System.in));
Socket clientSocket = new Socket ("127.0.0.1",6789);
DataOutputStream outToServer =
new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
sentence = inFromUser.readLine();
// while (true) {
outToServer.writeBytes(sentence + "\n");
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
//}
// clientSocket.close();
}

但是什么也没发生。

最佳答案

您在端口 1234 上打开了 ServerSocket,然后在 6789 上打开了 Socket。尝试使用相同的端口:)

关于java - 在后台接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44707804/

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