通过套接字java将对象广播到多个客户端

时间:2016-11-28 12:18:43

标签: java sockets objectinputstream objectoutputstream

我需要创建一个应用程序,客户端可以将消息(以对象的形式)发送到服务器,然后服务器将消息广播给其他客户端。

我为从服务器接收消息的客户端ObjectInputStream.readobject()遇到了一些问题。在线程中,在客户端监听服务器,打印"等待读取对象"在无限循环中打印出来,但是"读取对象"和"印刷"永远不会显示。那是为什么?

客户端的线程收听服务器

while (!terminate){

        try {
            System.out.println("Waiting to read object");
            ChatMessage msg = (ChatMessage) is.readObject();

            System.out.println("Read object");
            System.out.println(msg.toString());
            System.out.println("Printed");

        } catch (IOException e) {
            e.getMessage();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

写入服务器客户端

while(!terminate){

        String message = scanner.nextLine();

        if(message.equals("logout")){
            terminateProgram();
            return;
        }

        ChatMessage msg = new ChatMessage(name,message);

        try {
            os.writeObject(msg);
            os.flush();
        } catch (IOException e) {
            System.err.println("Sending message to server failed: " + e.getMessage());
        }
    }

从客户端读取消息并广播它们(服务器端)

while (!terminate) {

        try {
            Object obj = is.readObject();

            if (obj instanceof ChatMessage) {

                ArrayList<Socket> sockets = SingletonModel.getInstance().getSockets();

                for (Socket socketOne : sockets) {
                    if (socket != socketOne) {
                        System.out.println("We here");
                        os = new ObjectOutputStream(socketOne.getOutputStream());
                        os.writeObject(obj);
                        os.flush();
                        System.out.println("We done");
                    }

                }

1 个答案:

答案 0 :(得分:0)

我试图在你的代码中找到这个 ObjectInputStream.readobject(),你提到它但没有显示它。

在服务器端,您以这种方式发送对象(请注意,不要忘记序列化对象):

class Message implements Serializable{
  public String getMessage(){
   return "message";
}
}
ServerSocket serverSocket = new ServerSocket(3451);
  Socket server = serverSocket.accept();
  ObjectOutputStream outs = new ObjectOutputStream(server.getOutputStream());
            outs.writeObject(new Message());

在客户端,您应该以这种方式检索对象

  // or, Socket client = new Socket(InetAddress.getLocalHost(), 3451);
 Socket client = new Socket("localhost", 3451);
 InputStream inFromServer = client.getInputStream();
   ObjectInputStream ins = new ObjectInputStream(inFromServer);
          try {
              Message message= (Message ) ins.readObject();
          } catch (ClassNotFoundException ex) { }