美女镇楼.jpg
前端部分
<body></body>
<script>
// 模拟登陆
console.log("用户登录中");
let id = new Date().getTime();
console.log("用户" + id + "登陆成功");
//WebSocket实例化
var ws = new WebSocket("ws://localhost:8181");
// 创建当前玩家
let player = createNewPlayer(id);
// ws连接上后发送玩家id信息
ws.onopen = function (e) {
//成功连接服务器回调
ws.send(JSON.stringify({id: id}));
console.log('客户端(client):与服务器的连接已打开')
}
// 简单的设置,当前玩家的位置随着鼠标移动
document.addEventListener('mousemove', function(e){
player.style.left = e.pageX + "px";
player.style.top = e.pageY + "px";
// 移动鼠标的时候通知ws更新位置信息,这样其他玩家接收到就会实时更新
ws.send(JSON.stringify({id: id, left: e.pageX, top: e.pageY}));
})
// 定义除了自己的所有玩家
let players = {};
ws.onmessage = function(data){
data = JSON.parse(data.data);
// data结构类似 "{"id":1628156326172,"left":207,"top":410}"
// 如果id不是自己
if(data.id !== id){
let otherPlayer = null;
let otherId = data.id;
// 如果这个玩家不存在,说明是新加入的玩家,然后创建玩家;
if(!players[otherId]){
players[otherId] = createNewPlayer(otherId);
}
// 通过id获取传入的玩家
otherPlayer = players[otherId];
// 设置这个玩家的位置
otherPlayer.style.left = data.left + "px";
otherPlayer.style.top = data.top + "px";
}
}
// 创建一个新玩家
function createNewPlayer(id,left, right){
left = left || 10;
right = right | 10;
let player = document.createElement("div");
let color = getColor();
player.style.cssText = `position:fixed;width:10px;height:10px;top:${top}px;left:${left}px;background: ${color}`;
player.id = id;
document.body.append(player);
return player;
}
// 获取随机颜色
function getColor(){
return `rgb(${getColorH()},${getColorH()},${getColorH()})`;
}
// 获取0-255中的随机数()
function getColorH(){
return Math.round(Math.random() * 255);
}
</script>
nodejs 部分
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 8181 });//服务端口8181
let player = null;
var gamers = {};
wss.on('connection', function (ws, a) {
console.log('服务端:客户端已连接');
console.log(ws);
// 这个ws是什么?应该是当前的socket对象
// 通过console能看到开头一行<ref *1> WebSocket {
// 收到信息
ws.on('message', function (str) {
// 先处理一下
let obj = JSON.parse(str);
// obj结构类似 "{"id":1628156326172,"left":207,"top":410}"
player = ws;
// 如果gamers中不存在这个玩家
if(!gamers[obj.id]){
gamers[obj.id] = ws;
}
for (const key in gamers) {
if (Object.prototype.hasOwnProperty.call(gamers, key)) {
// 只要不是传进来值的玩家,就都将传值玩家信息发送过去,也就是说发送的消息只是一个玩家的,不是所有的。
if(obj.id != key){
// 这部是获取其他玩家的sokect对象;
const player = gamers[key];
player.send(JSON.stringify(obj));
}
}
}
});
});