时间:2023-07-22 10:51:01 | 来源:网站运营
时间:2023-07-22 10:51:01 来源:网站运营
从0开始用Nodejs做一个聊天室:node -v 与 npm -v,显示版本号就说明安装没有问题了。node-chat,在里面我们新建两个文件,一个是server.js,一个是index.html,注意后缀名。npm install -g cnpm --registry=https://registry.npm.taobao.orgcnpm install --save expresscnpm install --save socket.iovar app = require('express')(); //引入express库var http = require('http').Server(app); //将express注册到http中//当访问根目录时,返回Hello Worldapp.get('/', function(req, res){ res.send('<h1>Hello world</h1>');});//启动监听,监听3000端口http.listen(3000, function(){ console.log('listening on *:3000');});node server.jslocalhost:3000回车。index.html中输入以下代码:<!doctype html><html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>发送</button> </form> </body></html>server.js中写了根目录返回hello world,现在我们让它跳转到聊天室页面。将server.js中的app.get('/', function(req, res){ res.send('<h1>Hello world</h1>');});app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html');});node server.js。localhost:3000,已经跳转到聊天页面了。var app = require('express')();var http = require('http').Server(app);//new additionvar io = require('socket.io')(http);//endapp.get('/', function(req, res){ res.sendFile(__dirname + '/index.html');});//new additionio.on('connection', function(socket){ console.log('a user connected');});//endhttp.listen(3000, function(){ console.log('listening on *:3000');});index.html,添加下方标注内容:<!doctype html><html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> //new addition <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> //end </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>发送</button> </form> </body> //new addition <script src="/socket.io/socket.io.js"></script> <script> var socket = io() </script> //end</html>localhost:3000。就会有以下结果。li标签好了。在index.html的script中写一个方法,后面显示什么内容,就调用这个方法在面模板中插入一条li就好了。index.html中。function addLine(msg) { $('#messages').append($('<li>').text(msg));}index.html的script最前面,我们先弹出一个prompt()来询问用户的昵称,然后将用户名发送给后端,让后端告诉大家这个用户进来了接。join,然后后端会处理这个事件。<script> var name = prompt("请输入你的昵称:"); var socket = io() //发送昵称给后端 socket.emit("join", name) function addLine(msg) { $('#messages').append($('<li>').text(msg)); }</script>usocket数组来保存每一个用户的socket实例。join事件,在接收到昵称之后,将该用户的加入聊广播给所有用户。server.js代码如下:为了限制篇幅长度,从此处开始贴上来的代码有省略,请参考上下文确定位置。
var usocket = []; //全局变量...io.on('connection', function(socket){ console.log('a user connected') //监听join事件 socket.on("join", function (name) { usocket[name] = socket io.emit("join", name) //服务器通过广播将新用户发送给全体群聊成员 })});...index.html的script中添加以下代码,接受到新用户加入事件的处理:...//发送昵称给后端socket.emit("join", name)//收到服务器发来的join事件时socket.on("join", function (user) { addLine(user + " 加入了群聊")})...node server.js开启后端服务,然后访问localhost:3000,输入用户名iimTXXX的聊天。...//发送昵称给后端,并更改网页titlesocket.emit("join", name)document.title = name + "的群聊" //new addition...form的提交绑定一个事件,让它来处理新消息的发送。$('form').submit(function () { //solve code})var msg = $("#m").val()message吧,发送的数据就是msg。socket.emit("message", msg) //将消息发送给服务器$("#m").val("") //置空消息框form的提交事件。return false //阻止form提交form绑定的事件如下:...//当发送按钮被点击时$('form').submit(function () { var msg = $("#m").val() //获取用户恮的信息 socket.emit("message", msg) //将消息发送给服务器 $("#m").val("") //置空消息框 return false //阻止form提交})...message事件message吧。io.on('connection', function(socket){ console.log('a user connected') socket.on("join", function (name) { usocket[name] = socket io.emit("join", name) }) //new addition socket.on("message", function (msg) { io.emit("message", msg) //将新消息广播出去 })});message事件,将新消息呈现在面板中。...socket.on("join", function (user) { addLine(user + " 加入了群聊")})//接收到服务器发来的message事件socket.on("message", function(msg) { addLine(msg)})//当发送按钮被点击时$('form').submit(function () { var msg = $("#m").val() //获取用户输入的信息...整个过程相当于,用户a将自己的消息用message事件发送给服务器,服务器监听message事件接收其中的消息,将消息用事件message广播给全体用户,全体用户监听message事件,将事件接受到的消息呈现在聊天框中。PS:这一段是整个socket编程的核心,可以多读几遍细细理解。
node server.js。localhost:3000,回车,填写昵称为iimT。localhost:3000,回车,填写昵称为iimY。我是iimT, 一个固执的技术直男。
我的微博 : @_iimT
我的微信公众号 : iimT
个人博客:
关键词: