Java套接字服务器-客户端;卡在服务器端



这是我第一次在代码中找不到问题/错误,所以现在我问stackoverflow xD

我目前正在学习如何编写一个简单的服务器-客户端网络,以了解Java中的套接字和服务器套接字是如何工作的。因此,我写了一篇";程序";由服务器、客户端和处理程序类组成。Handler类负责接收客户端的消息并发送响应。从服务器发送到客户端运行良好,客户端接收到消息。但是,当客户端向服务器发送消息时,它不会收到任何消息。我正在使用的BufferedReader卡在readLine()请求上。

//This is the broken down version of what is happening in my Handler class
ServerSocket server = new ServerSocket(port); //These two lines of code actually happen in the Server class
Socket client = server.accept();              //but to simplify it I put them here
//Setting up the IO
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
//The Handler is waiting for the Reader to be ready and then prints the input
//Additionally, it sends a confirmation to the client
while(true) {
String input;
if(in.ready()){
if ((input = in.readLine()) != null) {
System.out.println(input);
out.println("Message Received");
if(input=="close") break;
}
}
}
//Expected output: "Message Received"
//Actual ouput: none, it gets stuck at in.ready() or in.readLine()

当我从客户端发送消息时,它应该只打印消息并向客户端发送确认,但如果我删除第一个if语句,它要么永远不会通过if(in.ready()){...}部分,要么会卡在if((input=in.readLine())!=null){...}处。我使用IntelliJ对其进行了调试,InputStream不包含readLine()所期望的任何消息或回车。我发现这真的很奇怪,因为服务器和客户端类的发送和接收部分(大部分(是相同的。

我唯一能想到的可能是这个问题的原因是客户端在发送消息时出现了问题。

//This is the broken down version of what is happening in my Client class
Socket client = new Socket();
client.connect(new InetSocketAddress("localhost",port));
//Setting up the IO
Scanner scanner = new Scanner(System.in); //I am using a Scanner for the message inputs
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
String input;
System.out.println("Enter the first Message: ");
while ((input = scanner.nextLine()) != null) {
String inServer;
System.out.println(input); //The input is correct
out.println(input); //I am suspecting it has something to do with this line or the PrintWriter
//This part works perfectly fine here while it does not in the Handler class
if (in.ready()) {
if ((inServer = in.readLine()) != null) {
System.out.println(inServer);
}
}
System.out.println("Enter next Message: ");
}
Expected output: inServer
Actual output: inServer

正如您所看到的,该部分的常规设置与Handler类中的设置相同,但在发送到服务器时似乎出现了问题。我不知道是服务器(我不这么认为,因为接收消息的相同代码在Client类中工作得很好(还是客户端,在这种情况下,PrintWriter或类似的东西一定有问题。

我已经在stackoverflow上看了其他/类似的问题,但没有找到任何能解决我问题的东西。如果有人想详细复制所有内容,则类的完整代码:(Pastebin链接(

服务器类

客户端类

处理器类

这个问题似乎已经得到了回答。。。这似乎与代码所在的IntelliJ项目有关。我不得不将其转移到一个新项目中,现在它可以工作了。这个问题现在已经解决了,如果有人想使用这段代码作为服务器客户端系统的基础,我会让pastebin链接继续工作。

我的建议是使用实现Reader的类的read((方法(BufferedReader就是其中之一(。语法如下:

String data = "";
int i;
while ((i = in.read()) != -1){
data += (char)i;
}

这种方式更加可靠,并且没有车厢返回问题。

最新更新