基于P2P的局域网即时通信系统
- 用户注册及对等方列表的获取:
- 对等方A启动后,用户设置自己的信息(用户名,所在组);
- 扫描网段中在线的对等方(服务器端口打开),向所有在线对等方的服务端口发送消息,接收方接收到消息后,把对等方A加入到自己的用户列表中,并发应答消息;
- 对等方A把回应消息的其它对等方加入用户列表。
- 双方交换的消息格式自己根据需要定义,至少包括用户名、IP地址。
- 发送消息和文件:用户在列表中选择用户,与用户建立TCP连接,发送文件或消息。
根据设计要求
要做的就是要获取到用一个局域网下所有在线设备IP地址,这个是最终目的建立TCP连接的前提。 方法:
- 利用UDP协议扫描网段中在线的对等方。向所有在线对等方的服务端口发送消息。举个例子就是A向B、C发送消息(数据包),这个数据包包括了用户名和IP地址。
- 这个时候B、C可以从数据包中解析出发送方的IP地址,然后他们各自将对等方A储存在自己的用户列表(即储存对应的用户名和IP地址)。
- B、C此时都分别向A(已经知道了IP地址)发送数据包,包括了自己的用户名和IP地址。A再将B、C存入自己的用户列表。
A与B之间,A与C之间都互相知道了对方的IP地址。此时可以建立TCP连接。
利用TCP连接和Socket通信原理,实现用户直接进行点对点,可靠的通信,使他们之间可以互相发送消息或文件。