# 在Angular中使用PeerJS进行P2P进行网络通讯 **Repository Path**: consolelog/demo-angular-p2p ## Basic Information - **Project Name**: 在Angular中使用PeerJS进行P2P进行网络通讯 - **Description**: 在Angular中使用PeerJS进行P2P进行网络通讯 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-08-11 - **Last Updated**: 2023-05-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 在Angular中使用PeerJS进行P2P进行网络通讯 - [服务器端](#服务器端) - [客户端](#客户端) - [其它](#其它) ## 服务器端 - 初始化目录 ```shell mkdir peerjs-server cd peerjs-server yarn init -y yarn add peer ``` - 在script中添加执行脚本: ``` "scripts": { "start:peer":"peerjs --port 9000 --key peerjs --path /myapp" } ``` - 启动服务器 ```shell yarn run start:peer ``` - 访问下面的地址,如果能返回一个json,并且其中包含 `name` 、 `description` 、 `website` 三个字段则说明成功: http://localhost:9000/myapp 例如: ```json { "name": "PeerJS Server", "description": "A server side element to broker connections between PeerJS clients.", "website": "https://peerjs.com/" } ``` ## 客户端 - 连接远程peer服务器: ```typescript this.peer = new Peer(this.peerId, {host: '192.168.1.152', port: 9000, path: '/myapp'}); ``` 1. `this.peerId` 这个值是节点的唯一id,是用来区分节点的,所以不能随便填。 但可以传空,这样peer服务器会随机生成一个uuid值并返回给客户端。 注意多个peer如果用了相同的id会冲突报错。 2. `192.168.1.152` 这个ip是我的peer服务器所部署的电脑ip,这个ip需要通讯的两个peer都可以访问到才行。 所以不能用127.0.0.1这种ip,应该用局域网或者是外网,总之要两边都能访问到。 3. `path` 对应的就是开启peer服务器时的选项 `--path /myapp` 的值。 - 节点直接互相连接 ```typescript this.conn = this.peer?.connect(this.otherPeerId); ``` 1. `this.peer` 就是前一步连接到peer服务器成功后返回的对象,如果上一步没有成功接下来的步骤都不能继续进行。 2. `this.otherPeerId` 是另一个节点的唯一id,也就是其它节点在执行上一步创建 `new Peer(xxx)` 时传入的peerId。 这个id全局唯一,每个节点都不能相同。如果传入的是自己的id也会报错。 3. 建立连接后,只要连接不销毁,两个节点就可以一直保持通讯。此时就算peer服务器关机了,两个节点之间的通讯也不会受影响。 - 向已连接的其它节点发送消息 ```typescript this.conn?.send(this.message); ``` 1. `this.message` 就是将要发送的字符串 2. 发送消息的前提是前两步必须成功,所以业务上要做异常处理 - 监听节点收到的消息 ```typescript this.peer.on('connection', (conn) => { conn.on('data', function (data) { console.log(`收到<${conn.peer}>发来的消息:${data}`); }); }); ``` 1. `conn` 是发送消息的节点的连接 2. `conn.peer` 是节点的唯一id 3. `data` 是收到的具体消息 ## 其它 开启 `peer服务器` 时还支持其它选项,具体请查看 [PeerJS-Server Github仓库](https://github.com/peers/peerjs-server)。 `peerjs` 客户端的Github仓库为: [PeerJS-Client Github仓库](https://github.com/peers/peerjs) 在连接 `peer服务器` 时,如果不传 `host`、`key`参数,则会自动连接到远程 [`PeerServer云服务`](https://peerjs.com/peerserver) 上。 请注意,这时会有很多人同时连接,可能会出现id冲突、网络环境较差,甚至是遭受攻击的情况。 `peerjs`还支持`视频`、`音频`等消息,具体请查看 [PEER JS 官方文档](https://peerjs.com/)。