1

I am writing the code for a server that would help two different applications in different platforms communicate with each other. To visualize it a bit it would be something like this :

App1<------>Server<------>App2

What server does is rear var1 from app2, write it to app1, then read var2 from app1 and write it to app2. Like this :

while(true){
var1 = app2stream.readInt();
app1stream.writeInt(var1);
var2 = app1stream.readDouble();
app2stream.writeDouble(var2);
}

My problem is that at some point i have this code at my server :

app1.accept();
app2.accept();

What this means is that no matter what, and given the fact that the server is always running, app1 is the one that should connect first since app1.accept() is a blocking method.

Is there any way around this? It would be great to allow the two applications to connect to the server regardless of who "came" first and then wait for the server to proceed with the above code. Can i use threads just for the accept() part and then pass the streams to the other thread? I read a bit about channels but got a bit buffled, any examples would be great.

4

4 回答 4

1

只有一个接受调用和一个服务器套接字。您可以在连接后确定哪个应用程序已连接。如果您无法从连接详细信息中获取它,请让他们发送一个身份验证码(无论如何可能是个好主意),您可以将其映射到您的应用程序。

于 2011-04-05T16:39:59.003 回答
1

使用蔚来

Selector它允许您使用该类执行非阻塞套接字(包括接受) 。

基本上,它为您提供了对系统库的更多本地访问权限以及无需多线程即可处理您的任务的能力。

于 2011-04-05T16:53:15.607 回答
0

You should probably treat them both the same unless they say otherwise.

For example when the each socket connects send a "what client?" message.

Then check whether the client responds with 1 or 2.

If both respond with 1 or something just disconnect both.

于 2011-04-05T16:36:56.177 回答
0

我认为做到这一点的“标准”方式是让服务器监听一个端口,当有消息进来时,立即启动一个新线程来处理它,然后再回去监听另一条消息。然后,正如 Glowcoder 所说,在同一个循环中进行所有连接,并在连接后弄清楚哪个是哪个。

我想另一种方法是拥有多个线程,每个线程都在不同的端口上侦听。我从来没有尝试过这样做,我不确定在建立连接之前是否会阻塞,所以你永远不会到达另一个线程。

于 2011-04-05T16:47:14.983 回答