我在将对象发送到服务器时遇到问题。现在,我有一个服务器设置并监听客户端。客户端连接,发送一个测试对象(只是一个字符串)并将其输出到命令行。它适用于发送的第一个字符串,但之后没有。
服务器(Hivemind.java):
// Open server socket for listening
ServerSocket ss = null;
boolean listening = true;
try {
ss = new ServerSocket(PORT_NUMBER);
} catch (IOException e) {
System.err.println("Cannot start listening on port " + PORT_NUMBER);
e.printStackTrace();
}
// While listening is true, listen for new clients
while (listening) {
Socket socket = ss.accept();
ServerDispatcher dispatcher = new ServerDispatcher(socket);
dispatcher.start();
}
// Close the socket after we are done listening
ss.close();
服务器线程(ServerDispatcher):
public ServerDispatcher(Socket socket) {
super("ServerDispatcher");
this.socket = socket;
}
public void run() {
System.out.println("Client connected");
try {
input = socket.getInputStream();
objInput = new ObjectInputStream(input);
Object obj = null;
try {
obj = (String)objInput.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(obj);
} catch (IOException ex) {
Logger.getLogger(ServerDispatcher.class.getName()).log(Level.SEVERE, null, ex);
}
连接类(HivemindConnect.java):
public HivemindConnect(int port) {
this.port = port;
url = "localhost";
}
public HivemindConnect(int port, String url) {
this.port = port;
this.url = url;
}
public void connect() {
try {
socket = new Socket(url, port);
output = socket.getOutputStream();
objOutput = new ObjectOutputStream(output);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() {
try {
objOutput.close();
output.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(Object obj) {
try {
objOutput.writeObject(obj);
objOutput.flush();
} catch (IOException ex) {
Logger.getLogger(HivemindConnect.class.getName()).log(Level.SEVERE, null, ex);
}
}
客户顶部组件:
// When the TC is opened connect to the server
@Override
public void componentOpened() {
hivemind = new HivemindConnect(9001);
hivemind.connect();
}
private void btnSendActionPerformed(java.awt.event.ActionEvent evt) {
hivemind.send(txtText.getText());
}
// When the TC is closed close the connection to the server
@Override
public void componentClosed() {
hivemind.close();
}