-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();
}
而不是使用行号来标识从服务器类发送的消息,什么是更好的选择?
我想给你一个有用的评论,但你的问题是“什么是更好的选择?”简直太宽了 – ControlAltDel 2014-08-28 19:39:38
因为我觉得我对它进行了硬编码。如果我有超过3个信息从服务器传递到客户端会怎么样?假设我有10个来自服务器的信息。我不想写if(lineNo == 4)和(line == 5)直到10. – user2935569 2014-08-28 19:43:19
由于您使用的是ObjectInputStream,因此您可以将所需的值放入一个(可序列化的)对象中,发送。 Java会照顾你的订单。 – 2014-08-28 20:00:47