Day12
今日份内容:使用WebSocket制作基于Node.js的网络聊天室
WebSocket是一种基于TCP协议的通信技术,与传统HTTP有一定区别。
WebSocket
- 了解WebSocket通信机制
- 熟悉WebSocket API接口
- 使用WebSocket技术实现双向通信
- 了解Notification消息提醒机制
内容
- 配置Node.js环境
- 项目初始化
- 安装Express、WebSocket、node_uuid框架
- 服务端实现
- 客户端实现
代码
// index.js
var express = require('express');
const http = require('http');
const url = require('url');
const WebSocket = require('ws');
const uuid = require('node-uuid');
var app = express();
//下面会修改临时文件的存储位置
app.use(express.static('public'));
//设置http服务监听的端口号
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'), function() {
console.log("Express started on localhost:" + app.get('port') + ':press Ctrl-C to terminate.');
});
//浏览器访问localhost会输出一个html文件
app.get('/', function(req, res) {
res.type('text/html');
res.sendFile('./index.html');
});
const server = http.createServer(app);
const wss = new WebSocket.Server({
server
});
server.listen(8080, function listening() {
console.log('Listening on %d', server.address().port);
});
var connections = [];
var userList = [];
var chatList = [];
var headImages = ["head1", "head2", "head3", "head4", "head5"];
wss.on('connection', function connection(ws, req) {
var currentUser;
var client_uuid = uuid.v4();
connections.push({
"id": client_uuid,
"ws": ws
});
console.log('&&&&&client[%s]连接成功!&&&&&', client_uuid);
//用户连接时,获得在线用户列表
ws.send(getUsersOnLine());
ws.on('message', function incoming(message) {
let json = JSON.parse(message);
//当用户发出登录请求时
if (json.op == "login") {
let userName = json.userName;
let loginTime = new Date();
let index = Math.ceil(Math.random() * (headImages.length));
//封装登录用户信息,以便保存到WebSocket中
currentUser = {
'userName': userName,
'loginTime': loginTime,
'headImages': headImages[index]
};
userList.push({
"id": client_uuid,
"user": currentUser
});
console.log('########client[%s]登录成功########', currentUser);
broadCast(getUsersOnLine());
broadCastNotification(getNewUser(currentUser.userName), ws);
//发送用户登录会话
ws.send(getUserWithConnectionInfo(client_uuid));
} else if (json.op = "chat") {
let connectionId = json.connectionId;
let chatMessage = json.chatMessage;
let time = json.time;
let user = getUse