Java端口重用,Java Server - 多个端口?

I'm about to program a server but am wondering if what I have in mind is possible. My program will be outputting to multiple clients on multiple ports - each port can be accessed by multiple clients.

Normally I would use a threaded socket server, but in this case I need it working for multiple ports. The usage I have in mind is in a vague pseudocode below:

Start server

Listen for incoming connections on several ports

Identify the port being connected to

If port 1, start a thread listening to client and outputting message type x

If port 2, start a thread listening to client and outputting message type y

Hopefully that makes some sense and you can see what I'm trying to do. Simply put: listen to selected ports, create a threaded socket connection based on which port is being connected to.

Is this doable at all, or am I going to end up multi-threading threaded socket servers?

Edit: Changed wording to better reflect the question.

解决方案

I don't think it's possible to for a single instance of ServerSocket to listen to multiple ports. You can of course have multiple ServerSockets. However, as you already know, ServerSocket.accept blocks.

What you can use instead is a ServerSocketChannel. They're used in a similar way, but do not block.

If there are no pending connections when ServerSocketChannel.accept is called then it simply returns null.

You can use with a Selector which takes a set of channels and blocks until at least one has a pending connection.

I don't remember the specifics on how to use them, but this seems to be a decent code example.

edit: Here is my own example (pseudo-ish)

Selector selector = Selector.open();

int[] ports = {4000,4001,6000};

for (int port : ports) {

ServerSocketChannel server = ServerSocketChannel.open();

server.configureBlocking(false);

server.socket().bind(new InetSocketAddress(port));

// we are only interested when accept evens occur on this socket

server.register(selector, SelectionKey.OP_ACCEPT);

}

while (selector.isOpen()) {

selector.select();

Set readyKeys = selector.selectedKeys();

Iterator iterator = readyKeys.iterator();

while (iterator.hasNext()) {

SelectionKey key = (SelectionKey) iterator.next();

if (key.isAcceptable()) {

SocketChannel client = server.accept();

Socket socket = client.socket();

// create new thread to deal with connection (closing both socket and client when done)

}

}

}

// tidy up selector and channels

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值