Dumb question about java Sockets :can i make a client listener on the input stream while the client writes the first thing to the object?
InetAddress Address = InetAddress.getByName("172.24.3.154");
kkSocket = new Socket(Address, 2003);
out = new ObjectOutputStream(kkSocket.getOutputStream());
in = new ObjectInputStream(kkSocket.getInputStream());
public static <T> Object sendReceive(T obj) {
try {
out.writeObject(obj);
out.flush();
System.out.println("Client : " + obj.toString());
Object resp = in.readObject();
if (resp != null) {
System.out.println("Server : " + resp.toString());
}
return resp;
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
this is my Client method that i send a request to the Server.
out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
System.out.println("Server: S-a conectat :" + socket.getInetAddress());
Protocol protocol = new Protocol(server);
while (socket.isClosed() != true) {
Object response = protocol.processInput(in.readObject());
System.out.println("Server: message Received: " + getName());
if (response != null) {
out.writeObject(response);
out.flu开发者_运维百科sh();
} else {
out.writeObject(null);
out.flush();
}
}
this is what my server does. And it works too.my question is : Giving this setup for the sockets how can i make a separate listener for the client in order to send at a certain time one message to the client , while the client still functions normally ?
I tryied to create a new thread fo manage the input stream on the client side , but the app won`t start and it just gets stuck in the run method of the thread Thx.EDIT :
What I am doing is a multi client App whith sockets,using mutli threading.I have the code above and works for me, for calling the "sendReceive" method for making a request to the server and it returns something.What i am trying to do is when i receive a specific request i want to notify all the online clients.I applied the observer pattern like this: The server is Observable and the threads are Observers. when a specific request comes in i notify all the treads , but i cant get each threat to send to the clients immediately a message because the client doesn
t listen.Maybe I'm going with this on the wrong way.Can someone Help pls?
Either you need to use two sockets (each on their own port - asynchronous communication) if you have no idea when the server will send a message to the client, or you need a better defined protocol that knows when to read, and when to write (one socket - synchronous communication).
If you can't predict when the client will need to read from the socket, then your app won't be able to figure it out either. :)
In the two socket approach, you could have one thread per socket, so you don't have to worry about I/O blocking.
精彩评论