2014-08-28 249 views
-1

在我的服务器类中,我必须一次向所有连接的客户端发送几条不同数据类型的消息从服务器向多个客户端发送多条消息

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; 
     /* ... 
      ... 
      ... */ 
} 

在我的客户端类中,我使用了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(); 
    } 

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

+0

我想给你一个有用的评论,但你的问题是“什么是更好的选择?”简直太宽了 – ControlAltDel 2014-08-28 19:39:38

+0

因为我觉得我对它进行了硬编码。如果我有超过3个信息从服务器传递到客户端会怎么样?假设我有10个来自服务器的信息。我不想写if(lineNo == 4)和(line == 5)直到10. – user2935569 2014-08-28 19:43:19

+1

由于您使用的是ObjectInputStream,因此您可以将所需的值放入一个(可序列化的)对象中,发送。 Java会照顾你的订单。 – 2014-08-28 20:00:47

回答

0

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

如果使用字节缓冲区,这可能会帮助您:

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(); 
} 

这里一些示例代码来处理与插座的(客户)的InputStream传入的字节流:

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); 

好运!

相关问题