服务器没有收到消息 - Java

时间:2015-04-23 01:01:59

标签: java client server lan

我有一个服务器和一个客户端,在我的服务器UI中,我有3个JLabel使用MouseClick我与连接到我的服务器的个人客户端进行通信。当我点击JLabel1消息时会发送Client1Client1收到消息时它应该响应,但是当它从服务器收到消息时它没有响应服务器。希望有人指导我,我的代码有什么问题。

// SERVER

void connect_clients()
    {
        try {
            ServerSocket listener = new ServerSocket(7700);
            jButton1.setText("Server Running!");
            jButton1.setEnabled(false);
                while (true) {

                    socket = listener.accept();
                    socketList.add(socket);

             //RECIEVE METHOD FROM CLIENT WILL COME HERE.

                }

            }
        catch(IOException ex)
        {
            JOptionPane.showMessageDialog(null, "5"+ex);
        }
    }
 *******here when i click my jlabel1,message is goign to 1st client ,it should respond on seeing the message from client. but it is not.****




private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {                                     

    PrintWriter out;
     try {
         socket = socketList.get(0);
         //JOptionPane.showMessageDialog(null, socket);
         out = new PrintWriter(socket.getOutputStream(), true);
         out.println("PC 1");

     } catch (IOException ex) {
     JOptionPane.showMessageDialog(null, "1"+ex);}

// CLIENT

void connect_server() throws IOException
    {
        try {
            // TODO code application logic here
            String serverAddress = JOptionPane.showInputDialog(
                    "Enter IP Address of a machine that is\n" +
                            "running the date service on port 9090:");
            s = new Socket(serverAddress, 7700);

            while(true){
                BufferedReader input =
            new BufferedReader(new InputStreamReader(s.getInputStream()));
            String answer = input.readLine();
            System.out.println(answer);
                if(answer != null)
                {

                    //respond method to server will come here.
                    JOptionPane.showMessageDialog(null,"Answer is not null");
               }

            }

          }

1 个答案:

答案 0 :(得分:0)

您必须在循环外创建BufferedReader;实际上同时作为套接字。如果readLine()返回null,您应该关闭它。