Skip to content

Commit

Permalink
feat: 信令服务器搭建
Browse files Browse the repository at this point in the history
  • Loading branch information
wang1xiang authored and 王翔 committed Aug 3, 2023
1 parent 425bb2f commit 10112cd
Show file tree
Hide file tree
Showing 10 changed files with 255 additions and 0 deletions.
59 changes: 59 additions & 0 deletions signal/client/client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const btnConnect = document.querySelector('button#connect')
const btnLeave = document.querySelector('button#leave')
const inputArea = document.querySelector('textarea#input')
const btnSend = document.querySelector('button#send')

let socket
let room
let username

btnConnect.onclick = () => {
room = document.querySelector('input#room').value
username = document.querySelector('input#username').value
// 连接server 携带username和room
socket = io('http://localhost:80', {
query: { username, room },
}).connect()

socket.on('user_list', (userList) => {
console.log('当前房间用户列表', userList)
btnConnect.disabled = true
btnLeave.disabled = false
inputArea.disabled = false
btnSend.disabled = false
})

socket.on('leave', (room, user) => {
console.log(`${user}从房间${room}离开`)
btnConnect.disabled = false
btnLeave.disabled = true
inputArea.disabled = true
btnSend.disabled = true

socket.disconnect()
})

socket.on('message', (room, data) => {
const outputArea = document.querySelector('textarea#output')
outputArea.scrollTop = outputArea.scrollHeight //窗口总是显示最后的内容
outputArea.value = outputArea.value + data + '\r'
})

socket.on('disconnect', () => {
btnConnect.disabled = false
btnLeave.disabled = true
inputArea.disabled = true
btnSend.disabled = true
})
}

btnSend.onclick = () => {
var data = inputArea.value
data = username + ':' + data
socket.emit('message', room, data)
inputArea.value = ''
}

btnLeave.onclick = () => {
socket.emit('leave', room, username)
}
31 changes: 31 additions & 0 deletions signal/client/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简单信令服务器</title>
</head>
<body>
<div>
<label>用户名: </label>
<input type=text id="username"></input>
<label>房间: </label>
<input type=text id="room"></input>
<button id="connect">连接</button>
<button id="leave" disabled>离开</button>
</div>
<div>
<label>收到消息: </label><br>
<textarea disabled style="line-height: 1.5;" id="output" rows="10" cols="60"></textarea>
</div>
<div>
<label>发送消息: </label><br>
<textarea disabled id="input" rows="3" cols="60"></textarea>
</div>
<div>
<button id="send">发送</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.js"></script>
<script src="./client.js"></script>
</body>
</html>
12 changes: 12 additions & 0 deletions signal/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "signal",
"version": "1.0.0",
"type": "module",
"main": "index.js",
"license": "MIT",
"dependencies": {
"express": "^4.18.2",
"log4js": "^6.9.1",
"socket.io": "^4.7.2"
}
}
21 changes: 21 additions & 0 deletions signal/service/clients.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// 客户端管理类
export default class Clients {
data = []
constructor(initArray = []) {
this.data = initArray
}
add(user) {
if (!user || !user.username) return
if (this.data.some((v) => v.username === user.username)) {
return false
}
this.data.push(user)
return true
}
remove(username) {
this.data = this.data.filter((c) => username !== c.username)
}
get(username) {
return this.data.find((c) => c.username === username)
}
}
28 changes: 28 additions & 0 deletions signal/service/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import express from "express";
import http from "http";
import { Server as IO } from "socket.io";
/**
* 初始化 express
* @param app
* @returns
*/
export default function initApp() {
let app = express();
let http_server = http.createServer(app);
http_server.listen(80);

let io = new IO(http_server, {
path: "/",
cors: {
origin: "*"
}
});
http_server.on("listening", () => {
let addr = http_server.address();
if (addr) {
let port = typeof addr === "string" ? addr : addr.port;
console.log(`Listening on ${port}`);
}
});
return io;
}
16 changes: 16 additions & 0 deletions signal/service/enum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** 系统 on 消息 */
export const SOCKET_ON_SYS = {
/** 连接socket */
CONNECTION: 'connection',
/** 断开socket */
DISCONNECT: 'disconnect',
}
/** socket消息 */
export const SOCKET_EMIT = {
/** 用户列表 */
SYS_USER_LIST: 'user_list',
/** 发送消息 */
MESSAGE: 'message',
/** 离开房间 */
LEAVE: 'leave',
}
23 changes: 23 additions & 0 deletions signal/service/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import log4js from 'log4js'

log4js.configure({
appenders: {
file: {
type: 'file',
filename: 'socket.log',
layout: {
type: 'pattern',
pattern: '%r %p - %m',
},
},
},
categories: {
default: {
appenders: ['file'],
level: 'debug',
},
},
})

const logger = log4js.getLogger()
export default logger
35 changes: 35 additions & 0 deletions signal/service/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { SOCKET_EMIT, SOCKET_ON_SYS } from './enum.js'
import SocketRtc from './on.js'
import initApp from './config.js'
import Clients from './clients.js'
import logger from './logger.js'

// 初始化应用
let io = initApp()
// 内存存储连接用户信息
let clients = new Clients()

// 监听连接
io.on(SOCKET_ON_SYS.CONNECTION, (socket) => {
const { query } = socket.handshake
// 获取socket连接参数 username和room
const { username, room } = query

// 添加到房间
const nowUser = { userId: socket.id, username }
clients.add(nowUser)
// 房间管理
socket.join(room)
// 每次连接向房间发送用户列表
io.to(room).emit(SOCKET_EMIT.SYS_USER_LIST, clients.data)
// 收发消息事件
SocketRtc(socket, clients)

// 断开连接
socket.on(SOCKET_ON_SYS.DISCONNECT, () => {
logger.debug(`断开连接: ${username}`)
clients.remove(nowUser.username)
// 每次连接发送用户列表
io.to(room).emit(SOCKET_EMIT.SYS_USER_LIST, clients.data)
})
})
20 changes: 20 additions & 0 deletions signal/service/on.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { SOCKET_EMIT } from './enum.js'
import logger from './logger.js'
/**
* rtc 监听
* @param socket socket
* @param clients 用户
*/
export default function SocketRtc(socket, clients) {
socket.on(SOCKET_EMIT.MESSAGE, (room, data) => {
logger.debug(`收到消息: ${data}, 来自于房间: ${room}`)
socket.to(room).emit(SOCKET_EMIT.MESSAGE, room, data)
})

socket.on(SOCKET_EMIT.LEAVE, (room, username) => {
socket.leave(room)
logger.debug(`离开房间: ${username}, 来自于房间: ${room}`)

socket.emit(SOCKET_EMIT.LEAVE, room, socket.id)
})
}
10 changes: 10 additions & 0 deletions signal/socket.log
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
13:24:44 DEBUG - 收到消息: 王:你好, 来自于房间: 1
13:24:49 DEBUG - 收到消息: 李:hello, 来自于房间: 1
13:25:31 DEBUG - 收到消息: 刘:你们好, 来自于房间: 2
13:25:42 DEBUG - 收到消息: 陈:大家好,我是陈xx, 来自于房间: 2
13:25:57 DEBUG - 收到消息: 谢:大家好,我是谢xx, 来自于房间: 2
13:27:56 DEBUG - 断开连接: 李
13:27:57 DEBUG - 断开连接: 王
13:27:57 DEBUG - 断开连接: 刘
13:27:58 DEBUG - 断开连接: 陈
13:27:59 DEBUG - 断开连接: 谢

0 comments on commit 10112cd

Please sign in to comment.