python从socket做个websocket的聊天室server

时间:2022-08-18 10:51:58

下面的是server端:把IP改成自己的局域网IP:

  

#coding:utf8
import socket,select
import SocketServer
import hashlib,base64,time
from pprint import pprint #author:lijim
def f(key): s=key+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
sha1=hashlib.sha1(s)
dig=sha1.digest()
return base64.encodestring(dig).strip() def parse_data(msg):
code_length = ord(msg[1]) & 127 if code_length == 126:
masks = msg[4:8]
data = msg[8:]
elif code_length == 127:
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
return raw_str
def send_data(raw_str):
back_str = [] back_str.append('\x81')
data_length = len(raw_str) if data_length < 125:
back_str.append(chr(data_length))
else:
back_str.append(chr(126))
back_str.append(chr(data_length >> 8))
back_str.append(chr(data_length & 0xFF)) back_str = "".join(back_str) + raw_str
return back_str gmsg=None def m(cs,raddr):
print raddr
req= cs.recv(8*1024)
print 'request:\n',req
print '-'*20+'\n' tmplist=req.split("\r\n")
headers={}
get=tmplist.pop(0)
for i in tmplist:
if i.find(":") !=-1: item=i.split(":") headers[item[0]]=item[1].strip()
# pprint(headers)
key=headers.get("Sec-WebSocket-Key","")
print '-'*20
print 'key:',key
accept=f(key)
print '-'*20+'\n'
ends=websocktemplate%(accept,headers.get("Sec-WebSocket-Origin","NULL").strip(),headers.get("Host","").strip(),) print 'response:\n'
print ends
cs.send(ends)
print '-'*20
global gmsg
while 1:
try:
r,w,e=select.select([cs,],[],[],0.5)
if gmsg:
cs.send(send_data(str(raddr)+':'+gmsg))
gmsg=None if cs in r:
msg=cs.recv(8*1024)
if msg:
data=parse_data(msg) if data!='close':
gmsg=data
print '%s:%s'%(raddr,data)
cs.send(send_data(str(raddr)+':'+data))
else: break except:
cs.close() ## cs.shutdown(2)
## cs.close()
## except KeyboardInterrupt:
### sock.shutdown(1)
## sock.close()
## print 'stop.'
## break sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) address=("192.168.1.104",8888)
sock.bind(address)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.listen(20) websocktemplate=''.join(["HTTP/1.1 101 Switching Protocols\r\n"
,"content-type:charset=utf-8\r\n"
,"Upgrade:websocket\r\n"
,"Connection: Upgrade\r\n"
,"Sec-WebSocket-Accept:%s\r\n"
,"WebSocket-Origin:%s\r\n"
,"WebSocket-Location: ws://%s/WebManagerSocket\r\n"
,"WebSocket-Protocol:WebManagerSocket\r\n\r\n"]) import threading
while 1:
r,w,e=select.select([sock,],[],[],1)
print 'wait..'
if sock in r:
cs,raddr=sock.accept()
t=threading.Thread(target=m,args=(cs,raddr))
t.setDaemon(1)
t.start()

下面为html页面:

<html>
<head>
<meta charset='utf8'/>
<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://192.168.1.104:8888/";
try{
socket = new WebSocket(host);
socket.onopen = function(msg){ ; };
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>