第一种方法
1、安装socket.io和express
npm install socket.io
npm install --save express
2、创建package.json
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {}
}
3、新建index.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
4、新建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>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function() {
var socket = io();
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg) {
$('#messages').append($('<li>').text(msg));
});
});
</script>
</body>
</html>
5、测试
运行
node index
浏览器访问
http://localhost:3000
参考地址:https://www.w3cschool.cn/socket/socket-ulbj2eii.html
第二种方法
index.js
var http = require("http")
,socket = require("socket.io")
,fs = require("fs");
var app,io;
app = http.createServer(function(req, res) {
//读取本程序运行位置的client.html文件
fs.readFile(__dirname+"/index.html",function(err, data){
res.writeHead(200);//设置200HTTP状态
res.end(data);
});
});
//Http服务器绑定的端口
app.listen(3000);
io = socket.listen(app);
//设置socket.io日志级别
io.set("log level", 1);
//监听链接事件
io.sockets.on("connection",function(socket){
//响应客户端msg事件
socket.on("msg",function(data){
console.log("Get a msg from client ...");
//控制台输出接受到的数据,实际项目可无
console.log(data);
//把收到的信息广播出去
socket.broadcast.emit("chat message",data);
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>简易聊天室</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="/socket.io/socket.io.js"></script>
<script>
(function() {
var socket = io.connect('http://localhost:3000'); //端口与服务器一致
socket.on('chat message', function(msg) {
msgbox(msg.msg); //显示服务器推送信息到聊天窗口
});
window.sendMsg = function() {
var inpt = document.getElementById('put');
var str = inpt.value;
msgbox(str); //显示自己发送的信息到聊天窗口
socket.emit('msg', {
msg: str
}); //发送到服务器
inpt.value = ""; //清空发送消息窗口
inpt.focus(); //让焦点定位到发送消息窗口
}
function msgbox(str) {
document.getElementById('box').innerHTML += str + '<br />';
}
})();
</script>
<style type="text/css">
#box {
overflow: auto;
width: 500px;
height: 100px;
border: 1px solid #dcdcdc;
}
#put {
width: 430px;
}
</style>
</head>
<body>
<h2>简易聊天室</h2>
<div id="box"></div>
<input type="text" id="put" />
<input type="button" value="发送消息" onclick="sendMsg();">
</body>
</html>