发布时间:2021-06-29编辑:佚名阅读(1328)
Server.js代码
var http = require("http"); var url = require('url'); var fs = require('fs'); var port = 80; var server = http.createServer(function (request, response) { var path = url.parse(request.url).pathname; switch (path) { case '/': response.writeHead(200, { 'Content-Type': 'text/html' }); response.write('hello world'); response.end(); break; case '/index.html': fs.readFile(__dirname + path, function (error, data) { if (error) { response.writeHead(404); response.write("page doesn't exist - 404"); response.end(); } else { response.writeHead(200, { "Content-Type": "text/html" }); response.write(data, "utf8"); response.end(); } }); break; default: response.writeHead(404); response.write("page this doesn't exist - 404"); response.end(); break; } }); var io = require('socket.io')(server); io.on('connection', function (socket) { //Send Data From Server To Client socket.emit('message', { 'message': 'Hello this message is from Server' }); //Receive Data From Client socket.on('client_data', function (data) { socket.emit('message', { 'message': data.letter }); socket.broadcast.emit('message', { 'message': data.letter }); process.stdout.write(data.letter); //console.log(data.letter); }); }); server.listen(port, '0.0.0.0'); console.log('server is running and listening on port 80');
index.html代码
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>socket.io</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script src="https://cdn.socket.io/socket.io-3.0.5.js"></script> <script> var socket = io.connect('http://127.0.0.1:80'); socket.on('message', function (data) { $('#conversation').append('<br>' + data.message); }); $(document).ready(function () { $('#send').click(function () { var msg = $('#text').val(); socket.emit('client_data', { 'letter': msg }); }); }); </script> </head> <body> <input id="text" type="text" /><button id="send">发送</button> <div id="conversation"></div> </body> </html>
关键字: nodejs 简易 Socket.io 聊天室 开发
上一篇:Socket.io 400错误
下一篇:url.parse已弃用
0人
0人
0人
0人