1、socket:分为一个服务端(server)和一个客户端(client):
server.js:
const net = require("net");
const server = net.createServer();
//创建一个盒子将所有连接的用户存放在这个盒子里面
const clients = []
//用户连接服务器
server.on("connection",(client)=>{
//给每一个用户做一个标识 用来一会去做移除
client.id = clients.length;
clients.push(client);
//服务器接收消息
client.on("data",(data)=>{
//服务器将接收到的消息发送给所有的用户
clients.forEach(item=>{
if(item){
item.write(data)
}
})
})
//当用户离开的时候
client.on("close",()=>{
clients[client.id] = null;
})
})
server.listen(9008);
client:
const net = require("net");
const client = new net.Socket();
//可以让你获取控制台中书写的信息
const readline = require("readline");
//创建文件读写流
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
//客户端连接服务器
client.connect(9008,()=>{
//客户端接收服务端的消息
client.on("data",(data)=>{
console.log("服务器消息:"+data)
})
})
//可以让用户在控制台中进行书写 以及获取到控制台的信息
rl.on("line",(val)=>{
client.write(val);
})
2、socket.io:index.html为客户端,server为服务器(最优选择)(github=>socket.io=>http://socket.io=>learn=>Get=>npm init - y =>cnpm install express -S=>跟着步骤走)
server.js:
var app = require('express')(); var http = require('http').createServer(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); //当用户连接的时候 io.on('connection', function(socket){ console.log('有人来了'); //服务端接收客户端的消息 socket.on('sendMsg', function(msg){ io.emit('sendClientMsg', msg); }) //当用户离开的时候 socket.on('disconnect', function(){ console.log('我走了'); }); }); http.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; 100%; }
form input { border: 0; padding: 10px; 90%; margin-right: .5%; }
form button { 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>
</body>
</html>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
//客户端向服务端发送消息
$('form').submit(function(e){
e.preventDefault(); // prevents page reloading
//向服务器发送消息
socket.emit('sendMsg', $('#m').val());
$('#m').val('');
return false;
});
//客户端接收服务器的消息
socket.on('sendClientMsg', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
3、webSocket:index.html为客户端,server为服务端 (H5新增,有兼容性,需下载第三方的包:npm init -y cnpm install ws -S;github中,将文档copy下来进行修改即可)
server.js:
const WebSocket = require('ws');
//创建服务器
const server = new WebSocket.Server({ port: 9000 });
//连接服务器
server.on('connection', (client) =>{
//接收客户端的消息
client.on('message', (data)=>{
//将接收到的消息发送给所有客户端
server.clients.forEach((item)=> {
//检测用户是否存在
if (item.readyState === WebSocket.OPEN) {
item.send(data);
}
});
});
});
index.html:
<!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>
</head>
<body>
<input type="text" id="input"/>
<button id="btn">点击</button>
<ul id="list">
</ul>
</body>
</html>
<script>
//客户端连接服务器
var client = new WebSocket("ws://10.9.14.136:9000");
//接收服务器的消息
client.onmessage = function(e){
let msg = e.data;
var li = document.createElement("li");
li.innerText = '服务端的消息:'+msg;
list.appendChild(li)
}
//向服务器发送消息
btn.onclick = function(){
var val = input.value;
input.value = "";
client.send(val);
}
</script>
总结:(群聊逻辑)
①创建一个群
②将好友拉到这个群
③连接共同的服务器
④发送消息的时候将消息发送给服务器,服务器转发给包括自己的所有用户
①A用户发送一条消息=>服务器
②服务器接收消息后=>给所有用户发消息
③如果有用户断开链接,就不用给他发