客户端未收到服务器发送的消息

时间:2016-11-22 10:26:45

标签: java javafx

基本上我使用jfx进行客户端和服务器之间的通信所以检查我是否从服务器向客户端发送消息以停止他的工作。为了简化我的问题,我制作了这个示例程序。按下按钮后,服务器会向所有客户端发送Stop消息。这是我的代码

myController1上课

 public class myController1 extends Stage implements Initializable {
        @FXML TextArea snames;
        tcpserver server;
        public void initialize(URL arg0, ResourceBundle arg1) {
            server=new tcpserver(8088);
            Task<Void> t=new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    // TODO Auto-generated method stub
                    server.start();
                    return null;
                }
            };
            new Thread(t).start();
        }
        public void Pressed(ActionEvent E) throws IOException{
            server.sendToAll("Stop");
        }
    }

tcpclient上课

public class tcpclient {
    public static void main(String[] args){
        System.out.println("Running");
        String hostName="127.0.0.1";
        int port=8088;
        try {
            Socket clientSocket = 
                      new Socket(hostName, port);
            while(true)
            {

                BufferedReader inFromServer=new 
                         BufferedReader(new 
                                 InputStreamReader(clientSocket.getInputStream()));
                    String FromServer=inFromServer.readLine(); 
                System.out.println("From Server "+FromServer); 
                if(FromServer.equals("Stop"))
                {
                    break;
                }   
            }   
            clientSocket.close();
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

sendToAll向所有连接的客户端发送消息的功能

public void sendToAll(String message) throws IOException{
        for(Socket client : clientsSockets)
        {
            System.out.println(":"+message);
            DataOutputStream outToServer =  null;
            outToServer = new 
                    DataOutputStream(client.getOutputStream()); 
            outToServer.writeBytes(message);

        }
    }

0 个答案:

没有答案