In First class have method “listen” which listening client socket
public void listen() throws IOException {
while (true) {
socket = this.serverSocket.accept();
DataOutputStream out = new DataOutputStream( socket.getOutputStream() );
this.outputStreams.put(socket, out);
Thread miltiServer;
miltiServer = new Thread() {
@Override
public void run() {
InputStream sin = null;
try {
sin = socket.getInputStream();
ObjectInputStream in = new ObjectInputStream(sin);
message = (AgentData) in.readObject();
} catch (ClassNotFoundException ex) {
} catch (IOException ex) {
}
}
};
miltiServer.start();
}
In Second class i need to read and analyze messages which recieved from client socket. I don’t know how to get messages in other class. I have idea to use Callable interface, but if i use it, return statement will exit from infinitive cycle.
An easy way for your socket listener to communicate the messages to your
Secondclass is through aBlockingQueue. The listener would read from the socket input stream and callqueue.put(...)to add any messages to the queue.Then the Second class would be in a loop calling
queue.take();which would return each message when it is added to the queue. If you want unlimited messages to be queued thenLinkedBlockingQueuewould work. If you want to throttle the messages then a bounded queue such asArrayBlockingQueuemight be more appropriate.Both threads would need to share the same
BlockingQueueso you will need to construct it and pass it to both threads or put a method on yourSecondclass named something likeaddMessage(...)and theBlockingQueuewould be inside of yourSecondclass. Then the listener would callsecond.addMessage(...);.