我正在创建一个客户端服务器,如下所示:
服务器
侦听器线程守护程序(始终侦听传入连接)
与客户端连接发送/接收数据的服务对象
客户端(一个或多个):
可能有很多客户端实例
但是,在建立连接后的任何一方,都需要永远创建ObjectOutputStream类型的构造函数。 ObjectInputStream的。谷歌搜索显示this和this。我按照以下步骤: 1.首先创建ObjectOutputStream 冲洗它 3.创建第二个ObjectInputStream
但这对我不起作用。不知道为什么??
服务器:
侦听器线程/守护程序:
Socket connSocket;
try {
ServiceListener.serverSocket = new ServerSocket(listenPort);
System.out.println("Listening on port: " + listenPort);
while (true) {
connSocket = serverSocket.accept();
nodeList.add(connSocket);
System.out.println("Accepted connections ( " + connSocket + "):" + getConnectedNodeCount());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
服务器线程(接受连接后)
for (int i=0; i<listenerObj.getConnectedNodeCount(); i++) {
try {
System.out.println(listenerObj.nodeList.get(i));
serviceTx = new ObjectOutputStream(listenerObj.nodeList.get(i).getOutputStream());
serviceTx.flush();
serviceRx = new ObjectInputStream(listenerObj.nodeList.get(i).getInputStream());
String rxMsg = (String) serviceRx.readObject();
if (rxMsg.equals("HELLO")) {
System.out.println("Service received: " + rxMsg);
serviceTx.writeObject((Object) "HELLO");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
客户端:
try {
System.out.println("Creating Node socket...");
clientSocket = new Socket(getServerIp(), getServerPort());
nodeTx = new ObjectOutputStream(clientSocket.getOutputStream());
nodeTx.flush();
nodeRx = new ObjectInputStream(clientSocket.getInputStream());
System.out.println("Connected to " + getServerIp() + ":" + getServerPort());
do {
String outBoundMsg = new String();
outBoundMsg = "HELLO";
System.out.println("Node sending \"" + outBoundMsg + "\" to service");
nodeTx.writeObject(outBoundMsg);
nodeTx.flush();
String rcvdMsg = (String) nodeRx.readObject();
if(rcvdMsg.equals("HELLO")) {
System.out.println("++++ client says " + rcvdMsg + " ++++");
}
} while(false);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
服务器控制台输出:
starting Listener 11...
Service Function started !!
Listening on port: 2244
Accepted connections ( Socket[addr=/127.0.0.1,port=62994,localport=2244]):1
客户端控制台:
Creating Node socket...
答案 0 :(得分:-2)
我会将do {} while(false)更改为do {} while(true)否则将while循环仅运行一次并退出是没有意义的,即do-while(false)循环行为就好像它不存在一样。