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

爪76

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

我目前正在学习如何编写一个简单的服务器-客户端网络,以了解Java中的套接字和服务器套接字是如何工作的。因此,我编写了一个由Server,Client和Handler类组成的“程序”。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()我发现这很奇怪,因为Server和Client类的发送和接收部分都是(大部分)相同。

我唯一想到的可能是此问题的原因,即客户端在某种程度上无法发送消息。

//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类中也可以正常工作)还是Client,在这种情况下,PrintWriter必定是一个问题或类似的东西。

我已经在stackoverflow上查看了其他类似问题,但没有找到任何可以解决我问题的方法。如果有人想详细复制所有内容,则提供类的完整代码:(Pastebin链接)

服务器类

客户类

处理程序类

爪76

好吧,看来问题已经解决了……似乎与代码所在的IntelliJ项目有关。我不得不将其移至新项目中,现在它可以工作了。该问题现在已解决,如果有人想将此代码用作服务器-客户端系统的基础,我将保持pastebin-links正常工作。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章