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实现简单的通信的更多相关文章

  1. Pomelo实现最简单的通信-egret。

    昨天因为需要开始学习Pomelo 做H5游戏的服务端. 因为个人学习习惯,我从来不适合去跟着文档看.一般我直接是看下大概的API,但是Pomelo的API全部都是英文的. 昨天我就告诉自己用一下午时间 ...

  2. WebSocket实现web即时通信(后端nodejs实现)

    WebSocket实现web即时通信 一.首先看一下,HTTP.ajax轮询.long poll和WebSocket的区别: 1.HTTP 协议(短连接):一个 Request 一个 Response ...

  3. 使用Java实现简单串口通信

    最近一门课要求编写一个上位机串口通信工具,我基于Java编写了一个带有图形界面的简单串口通信工具,下面详述一下过程,供大家参考 ^_^ 一: 首先,你需要下载一个额外的支持Java串口通信操作的jar ...

  4. .NET Core微服务之路:利用DotNetty实现一个简单的通信过程

    上一篇我们已经全面的介绍过<基于gRPC服务发现与服务治理的方案>,我们先复习一下RPC的调用过程(笔者会在这一节的几篇文章中反复的强调这个过程调用方案),看下图

  5. (原创)如何使用boost.asio写一个简单的通信程序(一)

    boost.asio相信很多人听说过,作为一个跨平台的通信库,它的性能是很出色的,然而它却谈不上好用,里面有很多地方稍不注意就会出错,要正确的用好asio还是需要花一番精力去学习和实践的,本文将通过介 ...

  6. C#串口介绍以及简单串口通信程序设计实现

    C#串口介绍以及简单串口通信程序设计实现 周末,没事干,写个简单的串口通信工具,也算是本周末曾来过,废话不多,直接到主题 串口介绍 串行接口简称串口,也称串行通信接口或串行通讯接口(通常指COM接口) ...

  7. nodejs与websocket模拟简单的聊天室

    nodejs与websocket模拟简单的聊天室 server.js const http = require('http') const fs = require('fs') var userip ...

  8. Python网络编程02 /基于TCP、UDP协议的socket简单的通信、字符串转bytes类型

    Python网络编程02 /基于TCP.UDP协议的socket简单的通信.字符串转bytes类型 目录 Python网络编程02 /基于TCP.UDP协议的socket简单的通信.字符串转bytes ...

  9. JAVA WebSocKet ( 实现简单的前后端即时通信 )

    1, 前端代码 HTML5 部分 <!DOCTYPE html> <html> <head> <meta charset="utf-8"& ...

随机推荐

  1. 高仿Readhub小程序 微信小程序项目【原】

    # News #### 项目介绍微信小程序项目涉及功能 https://gitee.com/richard1015/News https://github.com/richard1015/News 高 ...

  2. Educational Codeforces Round 53 (Rated for Div. 2) C. Vasya and Robot

    题意:给出一段操作序列 和目的地 问修改(只可以更改 不可以删除或添加)该序列使得最后到达终点时  所进行的修改代价最小是多少 其中代价的定义是  终点序号-起点序号-1 思路:因为代价是终点序号减去 ...

  3. Android大学课件SQLite3 数据库操作

    一.数据库介绍 SQLite3:当有大量相似结构的数据需要存储的时候 . 其实SQLite3 就是一个文件,类似之前学过的MySQL SqlServer等. 二.SQLiteOpenHelper 是一 ...

  4. bzoj 2038: [2009国家集训队]小Z的袜子(hose) (莫队)

    Description 作为一个生活散漫的人,小Z每天早上都要耗费很久从一堆五颜六色的袜子中找出一双来穿.终于有一天,小Z再也无法忍受这恼人的找袜子过程,于是他决定听天由命……具体来说,小Z把这N只袜 ...

  5. MT【288】必要性探路

    已知$f(x)=e^x-\dfrac{1}{2}ax^2-b$(1)当$a=1,b=1$时,求$f(x)$在$[-1,1]$上的值域.(2)若对于任意实数$x$,$f(x)\ge0$恒成立,求$a+b ...

  6. MT【286】最佳有理逼近

    2017北大优秀中学生夏令营已知$\omega $是整系数方程$x^2+ax+b=0$的一个无理数根, 求证:存在常数$C$,使得对任意互质的正整数$p,q$都有$$|\omega-\dfrac{p} ...

  7. 【Loj116】有源汇有上下界最大流(网络流)

    [Loj116]有源汇有上下界最大流(网络流) 题面 Loj 题解 模板题. #include<iostream> #include<cstdio> #include<c ...

  8. 「SCOI2014」方伯伯的 OJ 解题报告

    「SCOI2014」方伯伯的 OJ 和列队有点像,平衡树点分裂维护即可 但是需要额外用个set之类的对编号查找点的位置 插入完了后记得splay,删除时注意特判好多东西 Code: #include ...

  9. luogu3278/bzoj3323 多项式的运算 (splay)

    mulx的操作,其实就是给r+1的系数+=r的系数,然后删掉r,把l~r-1向右移一位,再插一个0到原来的位置 splay维护区间加和区间乘就好了 (一定要注意做事的顺序,一件事都做完了再去做别的,否 ...

  10. luogu1330 封锁阳光大学 (dfs)

    给每一个联通块黑白染色(一条边两端点不同色),看是否能染 然后选那个出现次数比较少的颜色 #include<bits/stdc++.h> #define pa pair<int,in ...