websocket 一种通信协议

ajax/jsonp 单工通信

websocket 全双工通信 性能高 速度快


2种方式:

1、前端的websocket
2、后端的 socket.io

demo地址:github

一、后端socket.io

https://socket.io/

安装:

cnpm i socket.io

接收on  发送emit ——可以发送任意类型的数据

后端:

1、创建httpServer

2、创建wsServer var ws = io(httpServer);

3、连接

ws.on("connect",function(socket){

   		//45  发送或者接收
发送 socket.emit("名称",数据);
广播 socket.broadcast.emit("名称",数据);
接收 socket.on(名称,function(data——数据){ }); });

前端:

1、引入js src="/socket.io/socket.io.js"

2、连接

var ws = io("ws://ip:port");

3、发送接收 on/emit

聊天室:

chat.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
*{padding:0;margin:0;list-style:none;}
#div1{ position:relative;width:500px; height:400px; border:1px solid red;}
#text{ position:absolute;left:0;bottom:0;width:80%; height:100px;}
#btn1{ position:absolute;right:0;bottom:0;width:20%; height:100px;}
#ul1{width:100%; height:300px; background:#ccc; overflow-y:auto;}
#ul1 li{ line-height:30px; border-bottom:1px dashed red;}
</style>
<!--<script src="/socket.io/socket.io.js"></script>-->
<script src="https://cdn.bootcss.com/socket.io/2.1.1/socket.io.js"></script>
<script>//http://10.30.155.92
//var ws = io("ws://10.30.155.92:9000");
//var ws = io("http://10.30.155.92:9000");
//var ws = io();
var ws = io.connect("ws://10.30.155.92:9000");//标准写法 ws://
window.onload = function(){
var oUl = document.getElementById("ul1");
var oText = document.getElementById("text");
var oBtn = document.getElementById("btn1"); var name = prompt("请输入你的用户名")//"张三";
oBtn.onclick = function(){
//发送数据
var data = {name:name,value:oText.value};
ws.emit("msg",data); createLi(data);
}; //接收数据 1创建dom
ws.on("msg_all",function(data){
console.log(data);
createLi(data);
}); function createLi(data){
//创建dom
var oLi = document.createElement("li");
oLi.innerHTML = `<strong>${data.name}</strong> <span>${data.value}</span>` ;
oUl.appendChild(oLi);
oUl.scrollTop = oUl.scrollHeight; }
};
</script>
</head> <body>
<div id="div1">
<ul id="ul1">
<!--<li><strong>张三</strong> <span>聊天内容</span></li>-->
</ul>
<textarea id="text"></textarea>
<input id="btn1" type="button" value="发送"/>
</div>
</body>
</html>

chat.js

var http = require("http");
var io = require("socket.io");
var fs = require("fs"); //创建http服务
var httpServer = http.createServer(function(req,res){
var url = req.url;
fs.readFile("www"+url,function(err,data){
if(err){
res.end("404");
} else {
res.end(data);
}
}); }); httpServer.listen(9000); //创建websockt服务 var ws = io(httpServer); ws.on("connection",function(socket){
console.log("wsServer"); //接收数据
socket.on("msg",function(data){
console.log(data); //发送数据广播
socket.broadcast.emit("msg_all",data);
});
});

前端H5 WebSocket

ws: http

wss:https

前端配置:
var ws = new WebSocket("ws://ip:port");

ws.onopen = function(evt) {
console.log("Connection open ...");
ws.send("Hello WebSockets!");
}; ws.onmessage = function(evt) {
console.log( "Received Message: " + evt.data);
ws.close();
}; ws.onclose = function(evt) {
console.log("Connection closed.");
};

后端:npm i ws

npm i ws

https://www.npmjs.com/package/ws

var wss = new WebSocket({server:httpServer});

wss.on("connection",function(ws,req){

		发送 接收

		接收
ws.onmessage(function(ev){
//数据 ev.data }); 发送:
ws.send(数据); 数据 最好只能是字符串!!! });

exp:

h5.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script> var ws = new WebSocket("ws://localhost:9000"); //建立连接
ws.onopen = function(ev) {
console.log("连接成功");
}; //接收数据
ws.onmessage = function(ev) {
console.log( "接收数据",ev.data);//server--->client
//发送数据
//ws.send("client--->server");
try{
//只处理json
var json = JSON.parse(ev.data);
console.log(json);
if(json.type == "click"){
var oSpan = document.getElementById("s1");
oSpan.innerHTML = json.value;
}
}catch(e){ }
}; //连接关闭
ws.onclose = function(evt) {
console.log("连接关闭");
}; window.onload = function(){
var oBtn = document.getElementById("btn1"); oBtn.onclick = function(){
//发送数据 只能发送字符串
ws.send(JSON.stringify({type:"click",value:"abc"}));
}; } </script>
</head> <body> h5 WebSocket
<input id="btn1" type="button" value="发送"/><span id="s1">1111</span>
</body>
</html>
h5.js:
var http = require("http");
var WebSocket = require("ws");
var fs = require("fs"); //创建http服务
var httpServer = http.createServer(function(req,res){
var url = req.url;
fs.readFile("www"+url,function(err,data){
if(err){
res.end("404");
} else {
res.end(data);
}
}); }); httpServer.listen(9000); //创建websockt服务 var wss = new WebSocket.Server({ server:httpServer }); wss.on('connection', function connection(ws) {
console.log("wsServer");
//发送 send
ws.send("server--->client"); //接收
ws.on('message', function(message) { console.log(message); //ws.send(message);
//广播
wss.clients.forEach(function(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
}); });
});
爱我所爱无怨无悔

9、socket.io,websocket 前后端实时通信,(聊天室的实现)的更多相关文章

  1. WebSocket 时时双向数据,前后端(聊天室)

    https://blog.csdn.net/lecepin/article/details/54632749 实例内容 今天主要说一下微信的WebSocket接口以及在小程序中的使用. WebSock ...

  2. 使用node.js + socket.io + redis实现基本的聊天室场景

    在这篇文章Redis数据库及其基本操作中介绍了Redis及redis-cli的基本操作. 其中的publish-subscribe机制应用比较广泛, 那么接下来使用nodejs来实现该机制. 本文是对 ...

  3. 使用socket.io实现多房间通信聊天室

    websocket的实现有很多种,像ws和socket.io,这里使用的是socket.io来实现多房间的效果. 这里的使用没有使用socket.io官方提供的namespace和room,而是完全通 ...

  4. vue.js+socket.io+express+mongodb打造在线聊天

    vue.js+socket.io+express+mongodb打造在线聊天 在线地址观看 http://www.chenleiming.com github地址 https://github.com ...

  5. vue.js+socket.io+express+mongodb打造在线聊天[二]

    vue.js+socket.io+express+mongodb打造在线聊天[二] 在线地址观看 http://www.chenleiming.com github地址 https://github. ...

  6. HTML5新特性 websocket(重点)--多对多聊天室

    一.html5新特性  websocket(重点)--多对多聊天室 HTTP:超文本传输协议 HTTP作用:传输网页中资源(html;css;js;image;video;..) HTTP是浏览器搬运 ...

  7. java 用socket制作一个简易多人聊天室

    代码: 服务器端Server import java.io.*; import java.net.*; import java.util.ArrayList; public class Server{ ...

  8. 与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室

    原文:与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...

  9. 与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室

    原文:与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...

随机推荐

  1. javacript onclick事件中传递对象参数

    var user = {id:1, name:'zs', age:20}; var ele = '<a onclick="edit(' + JSON.stringify(user).r ...

  2. Error-MVC: 未能找到路径“D:\\DsWeb\DS.Web\dist\bin\roslyn\csc.exe”的一部分。

    ylbtech-Error-MVC: 未能找到路径“D:\\DsWeb\DS.Web\dist\bin\roslyn\csc.exe”的一部分. 1.返回顶部 1, “/”应用程序中的服务器错误. 未 ...

  3. Python 和 Scikit-Learn

    Reference:http://mp.weixin.qq.com/s?src=3&timestamp=1474985436&ver=1&signature=at24GKibw ...

  4. JAVA项目中引用Logback的方法

    一.简介 本文主要讲JAVA项目中引入Logback的方法. 二.解决 1.引入依赖. <!--Begin LogBack Log--> <!-- https://mvnreposi ...

  5. 一步步教你轻松学支持向量机SVM算法之案例篇2

    一步步教你轻松学支持向量机SVM算法之案例篇2 (白宁超 2018年10月22日10:09:07) 摘要:支持向量机即SVM(Support Vector Machine) ,是一种监督学习算法,属于 ...

  6. eureka服务注册发现流程和核心参数

    参数1:eureka.instance.lease-renewal-interval-in-seconds 参数2:eureka.instance.lease-expiration-duration- ...

  7. bootstrap table 的简单Demo

    暂时够用,不够用再补充 T_T script: <link rel="stylesheet" href="lib/bootstrap.min.css"&g ...

  8. jQuery - Detect value change on hidden input field

    You can simply use the below function, You can also change the type element. $("input[type=hidd ...

  9. Python定期删除文件、整理文件夹

    1.根据传入的参数,文件所在目录,匹配文件的正则表达式,过期天数进行删除,这些可写在配置文件del_file.conf. del_file3.py #!/usr/bin/env python # en ...

  10. CUDA编程之快速入门

    CUDA(Compute Unified Device Architecture)的中文全称为计算统一设备架构.做图像视觉领域的同学多多少少都会接触到CUDA,毕竟要做性能速度优化,CUDA是个很重要 ...