I am creating a chat application. The client sends messages to the sever, the server just receives the first message but not more.
Server reading Thread
private void read(ObjectInputStream ois) {
new Thread() {
@Override
public void run() {
try {
String[] contents = (String[]) ois.readObject();
MainContainer.gh.add(new JLabel(contents[0] + " : " + contents[1]));
} catch (Exception ex) {
System.out.println("Sorry.");
}
}
}.start();
}
Client write method
public void write(String[] contents) {
try {
oos.writeObject(contents);
} catch (Exception ex) {
System.out.println("Sorry");
}
}
Thanks in advance. If you need extra code, you may request for that. Thanks.
Your code hasn't a loop.
So it receive the first array named contents
then exit.
You should add a loop similar to this one
while (true) {
// Receive messages
}
The server code must run in a loop. From memory, the server thread should run something like this
while (running) {
// block until next request
Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// Read from in. Write to out. Your code here...
}
running
is usually a volatile
variable that may be set to signal from other threads that the program should stop. Or you could interrupt the thread. Also, prepare to let the user configure socket timeouts.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.