我使用 Node.js 创建了一个简单的协作白板绘图应用程序。一切似乎都正常。但是,我有点坚持一个小功能。
我想在浏览器中显示一条状态消息,显示有多少其他连接的用户。我已将以下代码添加到server.js文件到 io.sockets.on 连接和断开连接:
// Set connected user counter on connection
var $ipAddress = socket.handshake.address;
if (!$ipsConnected.hasOwnProperty($ipAddress)) {
$ipsConnected[$ipAddress] = 1;
count++;
socket.emit('connectedusers', {
count: count
});
}
// Set connected user counter on disconnect
if ($ipsConnected.hasOwnProperty($ipAddress)) {
delete $ipsConnected[$ipAddress];
count--;
socket.emit('connectedusers', {
count: count
});
}
然后在客户端的文件sketch.js中,我添加了以下内容来设置连接用户的变量并将其分配给 ID 以在 HTML 浏览器中显示:
// Set status
socket.on('connectedusers',
function (data) {
var status = "Drawing with " + ((data.count)-1) + " other people";
document.getElementById("status").innerHTML = status;
}
);
当客户端运行时,您会看到已连接用户的状态显示为 OK。但是,如果有新用户加入,则无需刷新页面即可更新状态。
这是完整的代码
Node.js 服务器(文件server.js)
// Using Express.js: http://expressjs.com/
var express = require('express');
// Create the app
var app = express();
// Set up the server
// process.env.PORT is related to deploying on Heroku
var server = app.listen(process.env.PORT || 3000, listen);
// This call back just tells us that the server has started
function listen() {
var host = server.address().address;
var port = server.address().port;
console.log('Youmeus Draw listening at http://' + host + ':' + port);
}
// Set the root the root directory from which to serve static assets in a directory named public
app.use(express.static('public'));
// WebSocket portion
var io = require('socket.io')(server);
// Set connected user counter variables
var count = 0;
var $ipsConnected = [];
// Register a callback function to run when we have an individual connection
// This is run for each individual user that connects
io.sockets.on('connection',
// We are given a WebSocket object in our function
function(socket) {
// Send connected message to the console
console.log("New client has connected: " + socket.id);
// Set connected user counter on connection
var $ipAddress = socket.handshake.address;
if (!$ipsConnected.hasOwnProperty($ipAddress)) {
$ipsConnected[$ipAddress] = 1;
count++;
socket.emit('connectedusers', {
count: count
});
}
// When this user emits, client side: socket.emit('otherevent', some data);
socket.on('mouse',
function(data) {
// Data comes in as whatever was sent, including objects
console.log("Received: 'mouse' " + data.x + " " + data.y + " " + data.px + " " + data.py);
// Send it to all other clients
socket.broadcast.emit('mouse', data);
}
);
// On disconnect
socket.on('disconnect', function() {
// Send disconnected message to the console
console.log("Client has disconnected");
// Set connected user counter on disconnect
if ($ipsConnected.hasOwnProperty($ipAddress)) {
delete $ipsConnected[$ipAddress];
count--;
socket.emit('connectedusers', {
count: count
});
}
});
}
);
客户端 HTML(文件index.html)
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Draw Sockets Example</title>
<script type="text/javascript" src="./assets/lib/jquery/js/jquery.min.js"></script>
<script type="text/javascript" src="./assets/js/socket.io.js"></script>
<script type="text/javascript" src="./assets/js/p5.min.js"></script>
<script type="text/javascript" src="./assets/js/sketch.js"></script>
<style>
#canvas {
z-index: 1;
position: absolute;
display: block;
border: none;
margin: 0;
overflow: hidden !important;
}
#status {
z-index: 2;
position: absolute;
display: block;
bottom: 17px;
left: 0;
right: 0;
height: 60px;
margin: 0 20px 0 20px;
padding: 0 5px 0 0;
font-family: Gotham, 'Helvetica Neue', Helvetica, Arial, 'sans-serif';
font-size: 30px;
color: black;
line-height: 130%;
text-align: left;
}
</style>
</head>
<body>
<!-- Status text field, for displaying connection information -->
<div id="status"></div>
</body>
</html>
客户端 JavaScript 代码(文件sketch.js)
// Keep track of our socket connection
var socket;
function setup() {
// Create the canvas.
let canv = createCanvas(window.innerWidth, window.innerHeight);
// Assign a CSS selector ID to the canvas element
canv.id('canvas');
// Start a socket connection to the server
socket = io.connect('http://192.168.1.100:3000', { transports : ['websocket'] });
// Set status
socket.on('connectedusers',
function (data) {
var status = "Drawing with " + ((data.count)-1) + " other people";
document.getElementById("status").innerHTML = status;
}
);
// We make a named event called 'mouse' and write an anonymous callback function
socket.on('mouse',
// When we receive data
function(data) {
console.log("Got: " + data.x + " " + data.y + " " + data.px + " " + data.py);
// Draw
stroke(20);
strokeWeight(4);
line(data.x, data.y, data.px, data.py);
}
);
}
function draw() {
// Nothing
}
function mouseDragged() {
// Draw
stroke(20);
strokeWeight(4);
line(mouseX, mouseY, pmouseX, pmouseY);
// Send the mouse coordinates. x, y, previous x, previous y
sendmouse(mouseX, mouseY, pmouseX, pmouseY);
}
// Function for sending to the socket
function sendmouse(xpos, ypos, pxpos, pypos) {
// We are sending!
console.log("sendmouse: " + xpos + " " + ypos + " " + pxpos + " " + pypos);
// Make a little object with x and y
var data = {
x: xpos,
y: ypos,
px: pxpos,
py: pypos
};
// Send that object to the socket
socket.emit('mouse', data);
}
// Window resize
function windowResized() {
resizeCanvas(window.innerWidth, window.innerHeight);
}