首先新建一个空的目录,通过npm安装nodejs-websocket:
npm install nodejs-websocket新建app.js文件:
var ws = require("nodejs-websocket"); ws.createServer(function(conn){ conn.on("text", function (str) { console.log("get the message: "+str); conn.sendText("the server got the message"); }) conn.on("close", function (code, reason) { console.log("connection closed"); }); conn.on("error", function (code, reason) { console.log("an error !"); }); }).listen(8001);通过node app.js启动,这样服务器就搭建好了。
另一个使用SocketIO的方案。尚未尝试,明天測试一下:
// Require HTTP module (to start server) and Socket.IO var http = require('http'), io = require('socket.io'); // Start the server at port 8080 var server = http.createServer(function(req, res){ // Send HTML headers and message res.writeHead(200,{ 'Content-Type': 'text/html' }); res.end('<h1>Hello Socket Lover!</h1>'); }); server.listen(8080); // Create a Socket.IO instance, passing it our server var socket = io.listen(server); // Add a connect listener socket.on('connection', function(client){ // Create periodical which ends a message to the client every 5 seconds var interval = setInterval(function() { client.send('This is a message from the server! ' + new Date().getTime()); },5000); // Success! Now listen to messages to be received client.on('message',function(event){ console.log('Received message from client!',event); }); client.on('disconnect',function(){ clearInterval(interval); console.log('Server has disconnected'); }); });版权声明:本文博客原创文章,博客,未经同意,不得转载。
转载于:https://www.cnblogs.com/bhlsheji/p/4625945.html
相关资源:数据结构—成绩单生成器