我有一个客户端 - 服务器应用程序。现在,我正在尝试测试从客户端向服务器发送消息,然后从服务器读取它们。我正在使用ObjectInputStream
和ObjectOutputStream
在客户端和服务器之间传输邮件对象。
但是,当我尝试从客户端编写对象时,会产生SocketException
。
服务器代码:
while (true) {
try {
log.trace("Waiting for connection.");
Socket clientSocket = socket.accept();
log.trace("Socket connected");
/* create thread */
new Thread(new RequestRunner(clientSocket, serverID)).start();
} catch (SocketTimeoutException e) {
log.trace("Socket timed out.");
socket.close();
break;
} catch (IOException e) {
log.error("Cannot accept connection...");
break;
}
}
服务器线程:
public class RequestRunner implements Runnable {
....
public RequestRunner(Socket socket, UUID serverID) {
client = socket;
this.serverID = serverID;
}
/**
* Start the thread for the request
*/
public void run() {
log.trace("Thread started for socket");
try {
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
} catch (IOException e) {
log.error("Cannot intialize streams...");
return;
}
while(client.isConnected()) {
/* initialize streams */
try {
/* read message */
Object obj = in.readObject(); // does not block
MessageFrame msg = (MessageFrame) obj;
processRequest(msg);
} catch (IOException e) {
; // triggers everytime
//log.error("IO error occured while trying to get input/output stream from socket");
} catch (ClassNotFoundException e) {
log.error("Cannot read MessageFrame");
}
}
}
}
客户代码:
public void init(int port) throws IOException {
log.trace("intializing to port " + port);
clientID = UUID.randomUUID();
socket = new Socket("0.0.0.0",port);
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());
}
public void sendEcho() throws Exception {
while(socket.isConnected()) {
try {
log.trace("Sending echo..");
msg = new EchoMessage(clientID);
curMsgID = msg.getMsgID();
out.writeObject(msg); // throws SocketException, socket closed
out.flush();
break;
} catch (SocketException e) {
log.error ("Cannot send echo.. socket closed.");
break;
} catch (IOException e) {
continue;
}
}
}
语句out.writeObject(msg)
导致ServerSocket
例外Socket closed
作为原因。并且服务器不注册从in.readObject()
接收对象。
netstat
显示已建立的连接,当我尝试编写对象时发生错误。
我做错了什么?
答案 0 :(得分:0)
您应该只有一个InputStream和一个OutputStream。
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
应该是:
out = client.getOutputStream();
in = client.getInputStream()
在从套接字获取流时,您应该在客户端代码中更改它。