SocketServer synchronization

Hi all,

I'm creating a multi-agent application that uses socket programming for

connecting its clients.

The application consists of a ServerSocket

that waits for the

clients to connect to it. The accept method is called within a thread.

The SynchEngine , that runs the thread, also creates the agent processes, each of which, as a client, try to connect to the ServerSocket.

The problem is that I run the thread to start the ServerSocket,

then create my agent processes, but the thread is run after the agent

creation. So the agent encounters connection refused error.

Any Idea how to synchronize the ServerSocket accept method

with the agent creations?

[730 byte] By [Hamed.Rafia] at [2007-11-27 3:32:52]
# 1

> The problem is that I run the thread to start the

> ServerSocket,

> then create my agent processes, but the thread is run

> after the agent

> creation. So the agent encounters connection refused

> error.

So don't do that! Start the accept thread, and make sure the ServerSocket exists, before starting anything that will try to connect.

ejpa at 2007-7-12 8:35:55 > top of Java-index,Core,Core APIs...
# 2
The problem is, how to find out that the ServerSocket exists!and is waiting for clients.Do you have any suggestions?
Hamed.Rafia at 2007-7-12 8:35:55 > top of Java-index,Core,Core APIs...
# 3
Create it in the thread-creating thread, then spin off a thread which runs the accept loop.
ejpa at 2007-7-12 8:35:55 > top of Java-index,Core,Core APIs...
# 4

Like this:

ServerSocket socket = new ServerSocket(1234);

// The ServerSocket exists now

new ClientThread().start();

There are more complicated ways too. Like if you insist on having the "new ServerSocket()" in another thread, use wait()/notify() to synchronize things. You could enhance the experience by wearing one of [url=http://en.wikipedia.org/wiki/Gag_(BDSM)]these[/url] while coding it. The masochist way of coding!

sjasjaa at 2007-7-12 8:35:55 > top of Java-index,Core,Core APIs...
# 5

Not much point. You need to know that the ServerSocket was created and bound successfully before you start accepting connections *and* before you start trying to connect to it. So put it in the main thread, or the constructor, or wherever conditions are such that you haven't created any of these threads yet.

ejpa at 2007-7-12 8:35:55 > top of Java-index,Core,Core APIs...