当套接字在java中读取输入时循环失败

时间:2014-03-05 02:51:27

标签: java sockets while-loop client-server client

所以我遇到了从客户端读取输入的问题。每当我使用我的if语句而没有在服务器类中包含while语句时,它都可以正常工作。有人能指出为什么这可能会失败吗?

服务器类:

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

public class Server {

    public static void main(String[] args) throws Exception
    {
        Server myServer = new Server();
        myServer.run();
    }

    public void run() throws Exception
    {

        //Initializes the port the serverSocket will be on
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The Server is waiting for a client on port 9999");
        //Accepts the connection for the client socket
        Socket socket = serverSocket.accept();

        InputStreamReader ir = new InputStreamReader(socket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message = br.readLine();
        //Confirms that the message was received
        System.out.println(message);

    //When this while is here.  The match fails and it goes to the else statement.
    //Without the while statement it will work and print "Received our hello message." 
    //when the client says HELLO.

     while(message != null)
     {
            if(message.equals("HELLO"))
            {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("Received our hello message.");
            }
            else
            {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("Did not receive your hello message");
            }
        }
    }
}

客户端类:

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

public class Client {

    public static void main(String[] args) throws Exception
    {
        Client myClient = new Client();
        myClient.run();
    }

    public void run() throws Exception
    {
        Socket clientSocket = new Socket("localhost", 9999);
        //Sends message to the server
        PrintStream ps = new PrintStream(clientSocket.getOutputStream());
        Scanner scan = new Scanner(System.in);
        String cMessage = scan.nextLine();
        ps.println(cMessage);
        //Reads and displays response from server
        InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message = br.readLine();
        System.out.println(message);        
    }

}

4 个答案:

答案 0 :(得分:2)

你永远不会在while循环中修改消息,所以你有一个无限循环。

尝试

while((message = br.readLine()) != null)

答案 1 :(得分:1)

您的代码工作正常,可以发送一条“HELLO”消息。 但是,就像^ Tyler指出的那样,如果你想继续发送消息,你需要在while循环中移动'while((message = br.readLine())!= null)'。

答案 2 :(得分:1)

你只在服务器端循环,而你忘了在客户端循环,我为你做了快速修复,也帮助你关闭了你的连接。

Server.java

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

public class Server {

    public static void main(String[] args) throws Exception
    {
        Server myServer = new Server();
        myServer.run();
    }

    public void run() throws Exception
    {

        //Initializes the port the serverSocket will be on
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The Server is waiting for a client on port 9999");
        //Accepts the connection for the client socket
        Socket socket = serverSocket.accept();

        InputStreamReader ir = new InputStreamReader(socket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message;
        //= br.readLine();
        //Confirms that the message was received

    //When this while is here.  The match fails and it goes to the else statement.
    //Without the while statement it will work and print "Received our hello message." 
    //when the client says HELLO.
        PrintStream ps = new PrintStream(socket.getOutputStream());
        while((message =br.readLine())!=null)
         {
             System.out.println(message);
                if(message.equals("HELLO"))
                {

                    ps.println("Received our hello message.");
                }
                if(message.equals("END"))
                {
                    ps.println("Client ended the connection");
                    break;
                }
                else
                {

                    ps.println("Did not receive your hello message");
                }
        }
        ps.close();
        br.close();
        ir.close();
        serverSocket.close();
    }
}

Client.java

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

public class Client {

    public static void main(String[] args) throws Exception
    {
        Client myClient = new Client();
        myClient.run();

    }

    public void run() throws Exception
    {
        Socket clientSocket = new Socket("localhost", 9999);
        //Sends message to the server
        PrintStream ps = new PrintStream(clientSocket.getOutputStream());
        Scanner scan = new Scanner(System.in);
        String cMessage ="";
        InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        while(!(cMessage.trim().equals("END"))){
        cMessage = scan.nextLine();
        ps.println(cMessage);
        //Reads and displays response from server
        String message = br.readLine().trim();
        System.out.println(message);
        }
        br.close();
        ir.close();
        scan.close();
        ps.close();
        clientSocket.close();
    }

}

答案 3 :(得分:0)

像你一样使用循环......

String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
    sleep(in);
    if(!in.ready()){
        break;
    }
}

我想出了一种骗子的方式。

private static void sleep(BufferedReader in) throws IOException {
    long time = System.currentTimeMillis();
    while(System.currentTimeMillis()-time < 1000){
        if(in.ready()){
            break;
        }
    }       
}

这可能很草率,但是如果你做一个等待一段时间的睡眠方法并且只是继续检查BufferedReader是否准备就绪。&#34;如果是,你可以爆发,但是当你再次出来检查时。 - 也许你可以只返回一个布尔值而不是检查两次,但概念就在那里。