gpt4 book ai didi

java - 服务器在客户端-服务器应用程序中未收到消息

转载 作者:行者123 更新时间:2023-12-01 11:09:26 26 4
gpt4 key购买 nike

在我的客户端-服务器应用程序中,客户端向服务器发送消息,服务器应该显示该消息。但在我的例子中,客户端只能发送,但服务器无法实现。

我尝试过不同的端口号(即 8080、8000、4444 等)。看起来socket可以建立连接,但是我真的不知道为什么服务器无法读取客户端的输入。

这是我的完整项目(我在这里忽略了两个应用程序的主类,因为我除了调用方法之外什么也没有):

EchoServer.java:

    package client.server;

import java.io.*;
import java.net.*;

public class EchoServer {

public EchoServer() {
}

public void establish() {
ServerSocket serverSocket = null;
try {

serverSocket = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Could not listen on port: 1234");
System.exit(-1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 1234");
System.exit(-1);
}
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(
clientSocket.getOutputStream(), true);
in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
} catch (IOException ioe) {
System.out.println("Failed in creating streams");
System.exit(-1);
}
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
if (inputLine.equals("Bye.")) {
break;
}
}
} catch (IOException ioe) {
System.out.println("Failed in reading, writing");
System.exit(-1);
}
try {
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
System.out.println("Could not close");
System.exit(-1);
}
}
}

EchoClient.java:

    package server.client;

import java.io.*;
import java.net.*;

public class EchoClient {

public EchoClient() {
}

public void establish() {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
//echoSocket = new Socket(InetAddress.getLocalHost(), 1234);
echoSocket = new Socket(InetAddress.getLocalHost(), 8080);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
try {
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
if (userInput.equals("Bye.")) {
break;
}
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
} catch (IOException ioe) {
System.out.println("Failed");
System.exit(
-1);

}

}
}

最佳答案

您的服务器不会将传入文本写入控制台,而只会返回到客户端,而客户端尚未处理来自服务器的传入文本。

(out不是System.out而是Socket.out!)

关于java - 服务器在客户端-服务器应用程序中未收到消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32548614/

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