WebSocket 是一种网络通信协议。RFC6455 定义了它的通信标准。
WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
创建简易的聊天室
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
引入socket.io.js
<script src="socket.io.js"></script>
<style>
body {
font-size: 14px;
}
#content{
width:300px;
height:200px;
border:1px solid red;
overflow: auto;
}
.left{
text-align: left;
}
.right{
text-align: right;
}
#content p{
border:1px solid green;
border-radius:10%;
}
</style>
</head>
<body>
<!-- 用户登录 -->
<p>
<input type="text" id="userName">
<button id="login">登录</button>
</p>
<!-- 聊天窗口 -->
<div id="content">
</div>
<!-- 发送按钮 -->
<p>
<input type="text" id="ipt">
<button id="send">发送 to who</button>
</p>
<button id="clos">断开连接</button>
<!-- 上线用户列表 -->
<ul id="list"></ul>
</body>
<script>
var socket;
var user = '';
var toWho = '';
login.onclick = function () {
socket = io('http://localhost:3000');
socket.emit('login', {userName: userName.value});
user = userName.value;
socket.on('userList', function (data) {
console.log(data);
var html = '';
for (x in data) {
html += '<li>' + data[x] + '</li>';
}
list.innerHTML = html;
});
socket.on("send", function (data) {
content.innerHTML += "<p class='left'>" + data.from + " : " + data.msg + "</p>"
});
}
send.onclick = function () {
socket.emit('send', {
to: toWho,
from: user,
msg: ipt.value
});
content.innerHTML += "<p class='right'>我:" + ipt.value + "</p>";
}
list.onclick = function (e) {
if (e.target.nodeName == "LI") {
toWho = e.target.innerHTML;
}
send.innerHTML = "发送 to " + toWho;
}
</script>
</html>
var http = require("http");
var fs = require("fs");
var io = require("socket.io");
var app = http.createServer(function (req, res) {
if (req.url == '/') {
fs.readFile('index.html', function (err, data) {
res.end(data);
});
} else if (req.url == '/socket.io.js') {
fs.readFile("socket.io.js", function (err, data) {
res.writeHead(200, {
"Content-type": "text/javascript"
})
res.end(data);
});
} else {
res.end('');
}
}).listen(3000);
console.log('server is success');
var ws = io(app);
var userObj = {};
ws.on('connection', function (socket) {
socket.on('login', function (data) {
userObj[data.userName] = socket;
var arr = [];
for (var i in userObj) {
arr.push(i);
}
ws.emit("userList", arr);
});
socket.on('send', function (data) {
userObj[data.to].emit('send', data);
});
});
// 全体广播,发送userList事件
// ws.emit("userList",arr)
// 全体广播除了自己
// socket.broadcast.emit("userList",arr);
// 只发给自己
// socket.emit("userList",arr)