webscoket通信初步(一)
只要动手做起来,多投入时间和精力、耐心去研究,以大多人的智商加google,平时遇到的大部分问题我们都是可以自己解决的,大部分的知识我们都是可以掌握的。
我们都知道http协议是单向请求的,无法实现双向通信,它只能从客户端发送请求,然后服务端再响应请求,无法做到服务端主动向客户端去推送消息。
尽管可以通过setTimeout/setInterval轮询的方式来不断去刷新获取服务端的数据,但是轮询的效率低,非常浪费资源。webscoket就是为了解决这一问题而存在的。
webscoket的特点:
1、建立在Tcp协议之上
2、与http协议有着很好的兼容性
3、通信高效,因为它的数据格式比较轻量、性能开销小
4、可以发送文本和二进制数据
5、没有同源限制
6、协议标识符是ws
简单的通信原理如下
客户端的实现:
浏览器端的实现
<!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>WebSocket</title>
</head>
<body>
<h1>Echo Test</h1>
<input id="sendTxt" type="text"/>
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript"> var WebSocket = new WebSocket("ws://localhost:8080");
WebSocket.onopen = function(){
console.log('websocket open');
document.getElementById("recv").innerHTML = "Connected";
}
WebSocket.onclose = function(){
console.log('websocket close');
}
WebSocket.onmessage = function(e){
console.log(e.data);
document.getElementById("recv").innerHTML = e.data;
}
document.getElementById("sendBtn").onclick = function(){
var txt = document.getElementById("sendTxt").value;
WebSocket.send(txt);
}
</script>
</body>
</html>
服务端实现:
nodejs搭建服务器,可以参考git上的《一起学nodejs》搭建服务器
文件目录下 npm install webscoket
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// put logic here to detect whether the specified origin is allowed.
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Make sure we only accept requests from an allowed origin
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept('', request.origin);
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log('Received Message: ' + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(reasonCode, description) {
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
参考资料:
客户端(浏览器端)实现参考阮一峰:http://www.ruanyifeng.com/blog/2017/05/websocket.html
webscoket通信初步(一)的更多相关文章
- win32 线程通信初步
// 线程通信机制.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #define NUM_THREADS 10 #include < ...
- 前端后端通信初步尝试(javascript - flask)
在某项目中,需要使用python flask做后端功能开发,web提供功能入口. 此时需要使用Ajax通信. 由于以前从未接触过网络传输,记录了一些基础知识. 资料参考<HTML5+CSS3+J ...
- 阿里云负载不支持 WebSocket 协议与 WSS 和 Nginx 配置问题
WebSocket 是 HTML5 下一种新的协议.它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的.它与HTTP一样通过已建立的TCP连接来传输数据,但是它和HTT ...
- node的socket.io类库概述
socket.io是一个简单的小类库,该类库实现的功能类似于node中的net模块所实现的功能. 这些功能包括websocket通信,xhr轮询,jsonp轮询等. socket类库可以接受所有与服务 ...
- Netty之WebSocket和四种IO介绍
Netty简介 一.什么是netty? 高性能 事件驱动 异步非堵塞 基于NIO的客户端,服务器端编程框架 稳定性和伸缩性 二.Netty的使用场景 高性能领域 多线程并发领域 异步通信领域 ...
- VsCode插件开发之插件初步通信
参考了Egret Wing,想像Egret Wing那样在上方titlebar最右边上面增加一个menu(这个menu相对于一个按钮,当点击这个按钮时会出现一个window弹框,这个window弹框里 ...
- 基于C/S架构的3D对战网络游戏C++框架_05搭建系统开发环境与Boost智能指针、内存池初步了解
本系列博客主要是以对战游戏为背景介绍3D对战网络游戏常用的开发技术以及C++高级编程技巧,有了这些知识,就可以开发出中小型游戏项目或3D工业仿真项目. 笔者将分为以下三个部分向大家介绍(每日更新): ...
- Azure底层架构的初步分析
之所以要写这样的一篇博文的目的是对于大多数搞IT的人来说,一般都会对这个topic很感兴趣,因为底层架构直接关乎到一个公有云平台的performance,其实最主要的原因是我们的客户对此也非常感兴趣, ...
- webScoket的浅短的认识
在一般的发送数据请求的时候都是用的http协议,但是对于类似即时聊天,需要客户端与服务器不间断的交互的时候对于http协议来说就不太适用了.因为http协议无法主动把数据发到客户端,而且客户端发送请求 ...
随机推荐
- cocos2dx九宫图使用方法
九宫格Sprite: itemBg = Scale9Sprite::create("pop/achieve_itembg.png");if(!itemBg)return false ...
- flask数据库的迁移
需要的插件:flask-migrate 在每次修改模型之后,将修改的东西映射到数据库中. 使用flask-migrate 必须借助flask_scripts,这个包的所有MigrateCommand ...
- 20155219&20155224 《信息安全系统设计基础》实验一 开发环境的熟悉
实验内容 实验两人一组,最多三人一组 可以使用自己的笔记本,也可以使用实验室台式机 使用实验箱作为超级终端. 实验中学到的知识点 交叉编译 宿主机与目标机 NFS 超级终端 file命令 实验步骤 实 ...
- 代码basic讲解
key1 import os g = os.walk(r'D:\Users\Quincy_C\PycharmProjects\S6')print(next(g))print(next(g)) 第一次n ...
- HDU 6015 Skip the Class 优先队列 map的使用
Skip the Class Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Tota ...
- django-dailyfresh
Hold on ,learn by myself! redis nosql - 不支持sql语法 - 存储数据都是KV形式 - Mongodb - Redis - Hbase hadoop - Cas ...
- codeforce 804B Minimum number of steps
cf劲啊 原题: We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each ...
- spring事务中出现oracle游标溢出的解决方案
本例事务中大量查询SQL语句,会导致oracle游标溢出:对于数据库游标出现解决方案:1.大量查询SQL语句取消事务,只针对插入/更新 做事务处理2.用临时表代替大量查询SQL语句推荐使用第二种方案
- nginx与Apache的优缺点
来源:http://itindex.net/detail/46414-apache-nginx 1.nginx相对于apache的优点: 轻量级,同样起web 服务,比apache 占用更少的内存及资 ...
- python 调试之assert and logging
断言 assert assert后面跟的表达式应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错. 如果断言失败,会抛出AssertionError def foo(s): n = int ...