java - 点对点套接字

标签 java sockets p2p

我正在使用套接字制作一个聊天桌面应用程序,我的目的是在客户端之间创建点对点通信。我的问题是这样的:

如果我拥有所有 IP 地址,我可以同时连接它们之间的客户端吗?

在我的项目中,每个客户端都有服务器套接字和套接字(客户端)。

例如 client_1 在端口 1001 监听连接,但同时可以连接到具有不同 IP 并监听不同端口的其他客户端。

现在我想知道,如果有经验的人可以告诉一下,如果我连接到一个客户端但其他客户端连接到我,是否可以连接到某个客户端并同时接收其他客户端的消息?

如果 Client_A 监听端口 1001 但想与 Client_B 聊天,则它通过指定 IP 和端口将自己连接到 Client_B;现在,Client_A可以同时接收来自连接到其端口的其他客户端的消息吗?可能吗?

如果有人可以帮助我,我也可以发布我的代码;但我认为这是我必须在这里解决的逻辑问题。

非常感谢。

最佳答案

听起来您在套接字架构方面遇到了一些困难。架构中的每个套接字对都将由一对唯一的 IP 地址确定。 Wikipedia says :

Communicating local and remote sockets are called socket pairs. Each socket pair is described by a unique 4-tuple consisting of source and destination IP addresses and port numbers, i.e. of local and remote socket addresses.3[4] As seen in the discussion above, in the TCP case, each unique socket pair 4-tuple is assigned a socket number

此外,根据this stackoverflow answer :

Simply, if I connect to the same web server twice from my client, the two connections will have different source ports from my perspective and destination ports from the web server's. So there is no ambiguity, even though both connections have the same source and destination IP addresses.

您的点对点聊天客户端网络绝对可以工作,并且客户端确实可以将他们收到的消息联合到其他客户端。您很可能希望使用 GUID 标记每条消息,以便客户端不会多次处理同一消息。

也许更有用的架构是发布/订阅架构。 PubNub 等实时网络允许您将消息发布到全局 channel ,并在订阅该 channel 的客户端上接收这些消息。在您的情况下,使用 their Java SDK ,发布消息就像这样简单:

Callback callback = new Callback() {
  public void successCallback(String channel, Object response) {
    System.out.println(response.toString());
  }
  public void errorCallback(String channel, PubnubError error) {
    System.out.println(error.toString());
  }
};
pubnub.publish("demo", "Hello World !!" , callback);

我希望这有帮助。干杯!

关于java - 点对点套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23297376/

相关文章:

java - Android 数据库应用程序出错

c - Linux 本地通信套接字 : Why is bind() not failing as expected?

java - 还有其他方法可以在java面板上输出网络视频流吗?

git克隆问题[套接字: Address family not supported by protocol ]

node.js - React Native - 如何让两个设备在连接到同一网络时相互通信?

java - Android float 操作按钮 : Resize inside icon

java - 树结构未正确打印

java - UML 中的特定数组类型?

p2p - Kademlia key 用于识别节点和数据是什么意思?

p2p - 比特币客户端如何确定第一个连接的IP地址?