如何让客户端为每个其他客户端创建一个套接字 [英] How to have clients create a socket for every other client

查看:133
本文介绍了如何让客户端为每个其他客户端创建一个套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助思考客户连接并与所有其他客户进行通信的设计。我想每个客户端都会同时需要一个ServerSocket来监听来自其他客户端的传入连接,以及一个Socket来启动与其他客户端的连接。

I need help thinking up a design where clients connect and communicate with all other clients. I'm thinking each client will simultaneously need a ServerSocket for listening for incoming connections from other clients and a Socket for initiating connections with other clients.

我在localhost上测试,所以如果我使用端口号来跟踪连接,我会遇到这种情况:

I'm testing on localhost, so if I use ports numbers to keep track of connections, I run into this scenario:

Socket A (OS assigned port: a) initiates connection with ServerSocket B (known port: 2222)
Both clients record that connection (a, 2222) is made
Socket B (OS assigned port: b) initiates connection with ServerSocket A (known port: 1111)
Both clients record that connection (b, 1111) is made

我们应该每对客户端有1个连接,所以上面是浪费。这就是我为什么要设置自己设置本地端口的原因:场景将改为连接(1111,2222)和(2222,1111),并且因为第二个是相同的,所以不保留。

We should have 1 connection per pair of clients, so the above is a wasteful. THAT'S why I'm thinking setting about setting local ports myself: the scenario would change to connections (1111,2222) and (2222,1111), and since the second is the same, it's not kept.

听起来合理吗?

推荐答案

为什么要求客户端设置它的本地端口?客户端,服务器套接字的工作方式有点不同。

Why do you require the client to set it's local port? The way client, server sockets work is a bit different.

基本上当你有客户互相交谈时,你得到的是,每个客户都有一个传入它将为其他客户端监听的端口(服务器套接字)。当客户端希望连接到不同的客户端时,它将始终使用此端口来发起请求。收到请求后,客户端将简单地接受连接并将其传递给处理逻辑(无论是线程还是NBIO类型逻辑)。在这种情况下,您不必在任何地方定义本地端口。

Essentially when you have clients talking to each other, what you're getting at is, every client has a incoming port (server socket) that it'll listen on for other clients. When a client wishes to connect to a different client, it'll always use this port to initiate the request. Upon getting the request, the client will simply accept the connection and pass it to the handling logic (be it a thread or NBIO type logic). In this scenario you don't have to define the local port anywhere.

我认为您要解决的问题之一是,如果连接是什么两个客户之间已经建立了?在这种情况下,双方都知道谁连接到并且不会建立新的连接。在这种情况下,您正在考虑实现自己的双向通信协议。

I think one of the issues that you're trying to solve is, what if a connection is already established between two clients? In that case, both parties know whom are the connected to and will not establish a new connection. In which case you're looking at implementing your own protocol for a two-way duplex communication.

这篇关于如何让客户端为每个其他客户端创建一个套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆