websocket实现简单的通信
websocket server端
#coding=utf8
#!/usr/bin/python import struct,socket
import hashlib
import threading,random
import time
import struct
from base64 import b64encode, b64decode connectionlist = {}
g_code_length = 0
g_header_length = 0 def hex2dec(string_num):
return str(int(string_num.upper(), 16)) def get_datalength(msg):
global g_code_length
global g_header_length print (len(msg))
g_code_length = ord(msg[1]) & 127
received_length = 0;
if g_code_length == 126:
#g_code_length = msg[2:4]
#g_code_length = (ord(msg[2])<<8) + (ord(msg[3]))
g_code_length = struct.unpack('>H', str(msg[2:4]))[0]
g_header_length = 8
elif g_code_length == 127:
#g_code_length = msg[2:10]
g_code_length = struct.unpack('>Q', str(msg[2:10]))[0]
g_header_length = 14
else:
g_header_length = 6
g_code_length = int(g_code_length)
return g_code_length def parse_data(msg):
global g_code_length
g_code_length = ord(msg[1]) & 127
received_length = 0;
if g_code_length == 126:
g_code_length = struct.unpack('>H', str(msg[2:4]))[0]
masks = msg[4:8]
data = msg[8:]
elif g_code_length == 127:
g_code_length = struct.unpack('>Q', str(msg[2:10]))[0]
masks = msg[10:14]
data = msg[14:]
else:
masks = msg[2:6]
data = msg[6:] i = 0
raw_str = '' for d in data:
raw_str += chr(ord(d) ^ ord(masks[i%4]))
i += 1 print (u"总长度是:%d" % int(g_code_length))
return raw_str def sendMessage(message):
global connectionlist message_utf_8 = message.encode('utf-8')
for connection in connectionlist.values():
back_str = []
back_str.append('\x81')
data_length = len(message_utf_8) if data_length <= 125:
back_str.append(chr(data_length))
elif data_length <= 65535 :
back_str.append(struct.pack('b', 126))
back_str.append(struct.pack('>h', data_length))
#back_str.append(chr(data_length >> 8))
#back_str.append(chr(data_length & 0xFF))
#a = struct.pack('>h', data_length)
#b = chr(data_length >> 8)
#c = chr(data_length & 0xFF)
elif data_length <= (2^64-1):
#back_str.append(chr(127))
back_str.append(struct.pack('b', 127))
back_str.append(struct.pack('>q', data_length))
#back_str.append(chr(data_length >> 8))
#back_str.append(chr(data_length & 0xFF))
else :
print (u'太长了')
msg = ''
for c in back_str:
msg += c;
back_str = str(msg) + message_utf_8#.encode('utf-8')
#connection.send(str.encode(str(u"\x00%s\xFF\n\n" % message))) #这个是旧版
#print (u'send message:' + message)
if back_str != None and len(back_str) > 0:
print (back_str)
connection.send(back_str) def deleteconnection(item):
global connectionlist
del connectionlist['connection'+item] class WebSocket(threading.Thread):#继承Thread GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" def __init__(self,conn,index,name,remote, path="/"):
threading.Thread.__init__(self)#初始化父类Thread
self.conn = conn
self.index = index
self.name = name
self.remote = remote
self.path = path
self.buffer = ""
self.buffer_utf8 = ""
self.length_buffer = 0
def run(self):#重载Thread的run
print('Socket%s Start!' % self.index)
headers = {}
self.handshaken = False while True:
if self.handshaken == False:
print ('Socket%s Start Handshaken with %s!' % (self.index,self.remote))
self.buffer += bytes.decode(self.conn.recv(1024)) if self.buffer.find('\r\n\r\n') != -1:
header, data = self.buffer.split('\r\n\r\n', 1)
for line in header.split("\r\n")[1:]:
key, value = line.split(": ", 1)
headers[key] = value headers["Location"] = ("ws://%s%s" %(headers["Host"], self.path))
key = headers['Sec-WebSocket-Key']
token = b64encode(hashlib.sha1(str.encode(str(key + self.GUID))).digest()) handshake="HTTP/1.1 101 Switching Protocols\r\n"\
"Upgrade: websocket\r\n"\
"Connection: Upgrade\r\n"\
"Sec-WebSocket-Accept: "+bytes.decode(token)+"\r\n"\
"WebSocket-Origin: "+str(headers["Origin"])+"\r\n"\
"WebSocket-Location: "+str(headers["Location"])+"\r\n\r\n" self.conn.send(str.encode(str(handshake)))
self.handshaken = True
print ('Socket %s Handshaken with %s success!' %(self.index, self.remote))
sendMessage(u'Welcome, ' + self.name + ' !')
self.buffer_utf8 = ""
g_code_length = 0 else:
global g_code_length
global g_header_length
mm=self.conn.recv(128)
if len(mm) <= 0:
continue
if g_code_length == 0:
get_datalength(mm)
#接受的长度
self.length_buffer = self.length_buffer + len(mm)
self.buffer = self.buffer + mm
if self.length_buffer - g_header_length < g_code_length :
continue
else :
self.buffer_utf8 = parse_data(self.buffer) #utf8
msg_unicode = str(self.buffer_utf8).decode('utf-8', 'ignore') #unicode
if msg_unicode=='quit':
print (u'Socket%s Logout!' % (self.index))
nowTime = time.strftime('%H:%M:%S',time.localtime(time.time()))
sendMessage(u'%s %s say: %s' % (nowTime, self.remote, self.name+' Logout'))
deleteconnection(str(self.index))
self.conn.close()
break #退出线程
else:
#print (u'Socket%s Got msg:%s from %s!' % (self.index, msg_unicode, self.remote))
nowTime = time.strftime(u'%H:%M:%S',time.localtime(time.time()))
sendMessage(u'%s %s say: %s' % (nowTime, self.remote, msg_unicode))
#重置buffer和bufferlength
self.buffer_utf8 = ""
self.buffer = ""
g_code_length = 0
self.length_buffer = 0
self.buffer = "" class WebSocketServer(object):
def __init__(self):
self.socket = None
def begin(self):
print( 'WebSocketServer Start!')
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
self.socket.bind(("0.0.0.0",12345))
self.socket.listen(50) global connectionlist i=0
while True:
connection, address = self.socket.accept() username=address[0]
newSocket = WebSocket(connection,i,username,address)
newSocket.start() #开始线程,执行run函数
connectionlist['connection'+str(i)]=connection
i = i + 1 if __name__ == "__main__":
server = WebSocketServer()
server.begin()
websocket client 浏览器
<!DOCTYPE html>
<html>
<head>
<title>WebSocket</title> <style>
html, body {
font: normal 0.9em arial, helvetica;
} #log {
width: 440px;
height: 200px;
border: 1px solid #7F9DB9;
overflow: auto;
} #msg {
width: 330px;
}
</style> <script>
var socket; function init() {
var host = "ws://127.0.0.1:12345/";
try {
socket = new WebSocket(host);
socket.onopen = function (msg) {
log('Connected');
};
socket.onmessage = function (msg) {
log(msg.data);
};
socket.onclose = function (msg) {
log("Lose Connection!");
};
}
catch (ex) {
log(ex);
}
$("msg").focus();
} function send() {
var txt, msg;
txt = $("msg");
msg = txt.value;
if (!msg) {
alert("Message can not be empty");
return;
}
txt.value = "";
txt.focus();
try {
socket.send(msg);
} catch (ex) {
log(ex);
}
} window.onbeforeunload = function () {
try {
socket.send('quit');
socket.close();
socket = null;
}
catch (ex) {
log(ex);
}
}; function $(id) {
return document.getElementById(id);
}
function log(msg) {
$("log").innerHTML += "<br>" + msg;
}
function onkey(event) {
if (event.keyCode == 13) {
send();
}
}
</script> </head> <body onload="init()">
<h3>WebSocket</h3>
<br><br> <div id="log"></div>
<input id="msg" type="textbox" onkeypress="onkey(event)"/>
<button onclick="send()">发送</button>
</body> </html>
websocket实现简单的通信的更多相关文章
- Pomelo实现最简单的通信-egret。
昨天因为需要开始学习Pomelo 做H5游戏的服务端. 因为个人学习习惯,我从来不适合去跟着文档看.一般我直接是看下大概的API,但是Pomelo的API全部都是英文的. 昨天我就告诉自己用一下午时间 ...
- WebSocket实现web即时通信(后端nodejs实现)
WebSocket实现web即时通信 一.首先看一下,HTTP.ajax轮询.long poll和WebSocket的区别: 1.HTTP 协议(短连接):一个 Request 一个 Response ...
- 使用Java实现简单串口通信
最近一门课要求编写一个上位机串口通信工具,我基于Java编写了一个带有图形界面的简单串口通信工具,下面详述一下过程,供大家参考 ^_^ 一: 首先,你需要下载一个额外的支持Java串口通信操作的jar ...
- .NET Core微服务之路:利用DotNetty实现一个简单的通信过程
上一篇我们已经全面的介绍过<基于gRPC服务发现与服务治理的方案>,我们先复习一下RPC的调用过程(笔者会在这一节的几篇文章中反复的强调这个过程调用方案),看下图
- (原创)如何使用boost.asio写一个简单的通信程序(一)
boost.asio相信很多人听说过,作为一个跨平台的通信库,它的性能是很出色的,然而它却谈不上好用,里面有很多地方稍不注意就会出错,要正确的用好asio还是需要花一番精力去学习和实践的,本文将通过介 ...
- C#串口介绍以及简单串口通信程序设计实现
C#串口介绍以及简单串口通信程序设计实现 周末,没事干,写个简单的串口通信工具,也算是本周末曾来过,废话不多,直接到主题 串口介绍 串行接口简称串口,也称串行通信接口或串行通讯接口(通常指COM接口) ...
- nodejs与websocket模拟简单的聊天室
nodejs与websocket模拟简单的聊天室 server.js const http = require('http') const fs = require('fs') var userip ...
- Python网络编程02 /基于TCP、UDP协议的socket简单的通信、字符串转bytes类型
Python网络编程02 /基于TCP.UDP协议的socket简单的通信.字符串转bytes类型 目录 Python网络编程02 /基于TCP.UDP协议的socket简单的通信.字符串转bytes ...
- JAVA WebSocKet ( 实现简单的前后端即时通信 )
1, 前端代码 HTML5 部分 <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...
随机推荐
- Spring Boot 构建电商基础秒杀项目 (十一) 秒杀
SpringBoot构建电商基础秒杀项目 学习笔记 新建表 create table if not exists promo ( id int not null auto_increment, pro ...
- python之旅5【第五篇】
装饰器详解 函数刚开始不解析内部,只是放进内存 装饰器是函数,只不过该函数可以具有特殊的含义,装饰器用来装饰函数或类,使用装饰器可以在函数执行前和执行后添加相应操作. 1 下面以一个函数开始,理解下面 ...
- Android app下载并安装
1 下载功能 //下载apk private void downloadApk(String apkUrl) throws PackageManager.NameNotFoundException ...
- BZOJ 1977 严格次小生成树(算竞进阶习题)
树上倍增+kruskal 要找严格次小生成树,肯定先要找到最小生成树. 我们先把最小生成树的边找出来建树,然后依次枚举非树边,容易想到一种方式: 对于每条非树边(u,v),他会与树上的两个点构成环,我 ...
- Android 简单调用摄像头
IDE: android studio3.1.2 界面: activity_main2.xml
- css标准文档流
css标准文档流 所谓的标准文档流指的是网页当中的一个渲染顺序,就如同人类读书一样,从上向下,从左向右.网页的渲染顺序也是如此.而我们使用的标签默认都是存在于标准文档流当中. 标准文档流当中的特性 空 ...
- 【BZOJ5417】[NOI2018]你的名字(线段树,后缀自动机)
[BZOJ5417][NOI2018]你的名字(线段树,后缀自动机) 题面 BZOJ 洛谷 题解 首先考虑\(l=1,r=|S|\)的做法,对于每次询问的\(T\)串,暴力在\(S\)串的\(SAM\ ...
- 【BZOJ5304】[HAOI2018]字串覆盖(后缀数组,主席树,倍增)
[BZOJ5304][HAOI2018]字串覆盖(后缀数组,主席树,倍增) 题面 BZOJ 洛谷 题解 贪心的想法是从左往右,能选就选.这个显然是正确的. 题目的数据范围很好的说明了要对于询问分开进行 ...
- 「SHOI2014」三叉神经树 解题报告
「SHOI2014」三叉神经树 膜拜神仙思路 我们想做一个类似于动态dp的东西,首先得确保我们的运算有一个交换律,这样我们可以把一长串的运算转换成一块一块的放到矩阵上之类的东西,然后拿数据结构维护. ...
- Nginx+Keepalived部署
-----------ReProxy-------------------------Client-----------192.168.56.200 nginx+keepalived 192.168. ...