app.js
var express=require('express'); var app=express(); var DB=require('./module/db.js'); app.set('view engine','ejs'); app.use(express.static('public')); //express里面使用socket.io var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(8000); app.get('/',function(req,res){ //res.send('首页'); res.render('index'); }) app.get('/chat',function(req,res){ //res.send('首页'); var name=req.query.name; res.render('chat',{ name:name }); }) //写socket.io 服务端 io.on('connection',function(socket){ console.log('有个客户端连接了'); socket.on('message',function(data){ io.emit('message',data); /*全部广播*/ }) })
index.ejs
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> <style> html { height: 100%; background: url("banner-bg_2x.jpg") no-repeat center center / 100% auto #1B1C3B; } .box{ 400px; height: 60px; display: flex; margin:200px auto; } .box input[type='text']{ flex: 1; height: 60px; border: 1px solid #eee; } .box button{ 100px; height: 64px; background: orange; color: #fff; border:none; cursor: pointer; } </style> <script src="jquery-1.11.3.min.js"></script> <script> $(function(){ $('.login').click(function(){ var name=$('#name').val(); if(name){ location.href='/chat?name='+name; }else{ alert('您的大名不对'); } }) }) </script> </head> <body> <div class="box"> <input type="text" placeholder="请输入您的大名" id="name"/> <button class="login">进入聊天室</button> </div> </body> </html>
chat.js
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title></title> <style> .inner{ max- 640px; margin: 0 auto; } h2 { text-align: center; background: #eee; color: red; height: 50px; line-height: 50px; } .chat{ padding:20px; border: 1px solid #f60; height: 500px; } .send{ 100%; bottom:5px; height: 44px; line-height: 44px; display: flex; overflow-x: hidden; } .send input[type='text']{ flex: 1; } .send input[type='button']{ 100px; } </style> <script src="/socket.io/socket.io.js"></script> <script src="jquery-1.11.3.min.js"></script> <script> $(function(){ var socket=io.connect('http://localhost:8000'); socket.on('message',function(data){ /*监听服务器广播的数据*/ $(".list").append(`<li><strong>${data.name}:</strong> ${data.msg}</li>`); $('#msg').val(''); $('.footer').get(0).scrollIntoView(true); }) //发送数据 $('#send').click(function(){ socket.emit('message',{ msg:$('#msg').val(), name:'<%=name%>' }) }) }) </script> </head> <body> <div class="inner"> <h2>小小聊天室</h2> <div class="chat" style="overflow-x: auto"> <ul class="list"> </ul> <p class="footer"> </p> </div> <div class="send"> <input type="text" id="msg"/> <input type="button" id="send" value="发送"/> </div> </div> </body> </html>