【发布时间】:2014-05-02 19:09:10
【问题描述】:
我正在尝试编写一个客户端-服务器应用程序,其中多个客户端可以在任何给定时间向服务器发送包含更新的对象。到目前为止,我设法将客户端连接到服务器并发送第一个对象,但我不能在以后发送对象(不建立新连接)。这是我的代码:
服务器:
ServerSocketChannel ssc = null;
try {
ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(port));
ssc.configureBlocking(true);
while (true) {
SocketChannel sc = ssc.accept();
ObjectInputStream ois = new ObjectInputStream(sc.socket().getInputStream());
Object obj = ois.readObject();
Client client = (Client)obj;
sc.close();
}
} catch (IOException | ClassNotFoundException e) {
} finally {
if (ssc != null) {
try {
ssc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户:
SocketChannel sc;
ObjectOutputStream oos;
try {
sc = SocketChannel.open();
sc.configureBlocking(true);
sc.connect(new InetSocketAddress(client.getPort()));
try {
/* While channel's socket is not connected */
while (!sc.finishConnect()) {}
/* Channel's socket is now connected */
oos = new ObjectOutputStream(sc.socket().getOutputStream());
sendClientObjectToServer();
}
catch (ConnectException e){}
} catch (IOException e) {}
finally {
if (sc != null) {
try {
sc.close();
oos.close();
} catch (IOException e) {}
}
}
public void sendClientObjectToServer() {
try {
oos.writeObject(client);
}
catch (IOException e){}
}
sendClientObjectToServer 方法第一次运行良好,但如果我稍后尝试调用它(按下 jbutton)会得到 ClosedChannelException。
编辑:找到solution。
【问题讨论】:
-
每次需要与服务器通信时,都需要与服务器建立开放连接。一种选择是不关闭连接,除非应用程序关闭。
-
while (!sc.finishConnect()) {}是主所憎恶的。如果要阻塞模式,为什么要使用非阻塞模式?
标签: java sockets objectoutputstream