从服务器向多个客户端发送多条消息

时间:2014-08-28 19:34:03

标签: java sockets

在我的Server类中,我必须立即向所有连接的客户端发送几条不同数据类型的消息。

 public class Server() { 

     private List<ClientT> client = new ArrayList<ClientT>();         
     private String strValue = "someText";                 
     private int intValue = 20;
     private int intValueTwo = 20;

     try {
            for(int i = 0; i < client.size(); i++) {
                client.get(i).output.writeObject(strValue);
                client.get(i).output.writeObject(intValue);
                client.get(i).output.writeObject(intValueTwo);
            }           
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    class ClientT extends Thread {
        private ObjectOutputStream output;
        /* ...
           ...
           ... */   
}

在我的Client类中,我使用lineNumbers来检测从服务器发送的消息。

  ObjectInputStream input;
  int lineNo = 0;
  String message = " ";
  try {     
        input = new ObjectInputStream(socket.getInputStream());

        while(true) {
            lineNo++;
            message = (Object) input.readObject();

            if(lineNo == 1) {
                //read first message from the server
            }
            else if(lineNo == 2) {
                //read second message from the server
            }
            else if(lineNo == 3) {
                //read third message from the server
            }   

    } catch (IOException exception) {
            System.out.println("Error: " + exception);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

不是使用行号来标识从服务器类发送的消息,还有什么更好的选择?

1 个答案:

答案 0 :(得分:0)

与任何TCP / UDP数据包一样,连接字节并将它们发送到应该知道协议的客户端,因此要读取多少字节以及何时,或者如果您更喜欢可变长度消息,则使用仍需要的分隔符由客户解析。

如果您使用ByteBuffer,这可能会对您有所帮助:

public static String getStringFromByteBuffer(ByteBuffer bb) { 
    StringBuilder message = new StringBuilder(); 
    int bytes;
    while(true) {
        try { 
            bytes = bb.get(); 
                // format the product of two bytes and a bitwise AND with 0xFF 
            message.append("\\x"+String.format("%02x", bytes&0xff)); 
        } catch (Exception e) { 
            break; 
        } 
    } 
    return message.toString(); 
} 

这里有一些SAMPLE代码用socket(客户端)输入流来处理传入的字节流:

    byte[] lengthArray = new byte [someSize]; 
    this.in.readFully(lengthArray, 0, 4); 
    this.busy = true; 
    ByteBuffer lengthBuffer = ByteBuffer.wrap(lengthArray);
    byte[] tcpArray = new byte[length]; 
    // read message from the remote parent peer of this instance
    this.in.readFully(tcpArray, 0, length); 
    // load message into ByteBuffer container for convenience 
    ByteBuffer tcpInput = ByteBuffer.wrap(tcpArray); 
祝你好运!