Reputation: 16656
I need to build an app where I have four servers running and one client send some packages to these servers, but these servers have to keep running all the time receiving something from the client(sender). So I create the both classes, client and server:
public class Server {
public Event receive(int port) {
Evento event = null;
try {
ServerSocket ss = new ServerSocket(port);
Socket s = ss.accept();
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
evento = (Evento) ois.readObject();
is.close();
s.close();
ss.close();
}catch(Exception e){
System.out.println(e);
}
return event;
}
}
public class Client {
public void send(Event event, int port) {
try {
Socket s = new Socket("localhost", 2002);
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(event);
oos.close();
os.close();
s.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
But as I said, I need these servers keep running all the time, if I test once, that's ok, but twice or more, don't. How could I do that ?
Upvotes: 0
Views: 96
Reputation: 6239
just add a do while block around the readObject. As a break condition you can check whether the message is something like "exit"..
cheers
Upvotes: 0
Reputation: 533820
The standard pattern is to create one thread for each connection. If you use one thread you can only read from one blocking connection.
Upvotes: 2