我的Java Server / Client程序只能在我运行它的第三次工作

时间:2016-03-04 15:43:11

标签: java networking server client

我是Java编程的新手,甚至是Java网络编程的新手,所以我确信这个问题很简单。我的程序基于提交按钮,该按钮将学生ID提交给服务器。

我运行程序的前两次它将与服务器建立连接,然后一切都会崩溃,它永远不会交换字符串。

但是,每运行一次,它就能完美地工作并按设计交换字符串。

客户端:

String currentButton = e.getActionCommand();
    if(currentButton == "submit"){
        try{
            Socket server = new Socket("Localhost",1234);
            InetAddress address=InetAddress.getLocalHost();

            System.out.println("Connected to "+server.getInetAddress());
            System.out.println("Connected to "+address);

            BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));

            PrintWriter pw = new PrintWriter(server.getOutputStream(), true);

            pw.println(student);

            while ((student = br.readLine()) != null) {
              System.out.println(student);
              pw.println("bye");

              if (student.equals("bye"))
                break;
            }
            br.close();
            pw.close();
            server.close();
        } catch (IOException ex){
            //ignore exception
        }
    }

服务器

class NETCW1S {
public static void main(String[] args) throws IOException {
    String student;
    ServerSocket serverSock = null;
    InetAddress address=InetAddress.getLocalHost();
    try{
        serverSock = new ServerSocket(1234);
        System.out.println("Waiting for client connection");
    } catch (IOException e) {
        System.err.println("Could not listen on port: 1234");
        System.exit(1);
    }
    Socket clientSock = null;
    try{
        clientSock = serverSock.accept();
    } catch (IOException e) {
        System.err.println("Accept Failed");
        System.exit(1);
    }
    while (true) {
        System.out.println("Connected to "+address);
        System.out.println("Waiting for client...");
        Socket client = serverSock.accept();

        System.out.println("Client from "+client.getInetAddress()+" connected.");

        Socket fromClientSocket = serverSock.accept();
        PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);

        BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));

        while ((student = br.readLine()) != null) {
            System.out.println("The message: " + student);

            if (student.equals("bye")) {
                pw.println("bye");
                break;
            } else {
                student = "Server returns " + student;
                pw.println(student);
            }
        }
        pw.close();
        br.close();

        fromClientSocket.close();
    }
}   

非常感谢提前!

1 个答案:

答案 0 :(得分:0)

服务器应该在循环内只有一个accept()调用。客户端需要在某个时刻进行connect()调用 - 现在它似乎根本不与客户端通信。