python從socket做個websocket的聊天室server

下面的是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]) & 127if 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 = 0raw_str = ''for d in data:raw_str += chr(ord(d) ^ ord(masks[i%4]))i += 1return 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_strreturn back_strgmsg=Nonedef m(cs,raddr):print raddrreq= cs.recv(8*1024)print 'request:\n',reqprint '-'*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 '-'*20print 'key:',keyaccept=f(key)print '-'*20+'\n'ends=websocktemplate%(accept,headers.get("Sec-WebSocket-Origin","NULL").strip(),headers.get("Host","").strip(),)print 'response:\n'print endscs.send(ends)print '-'*20global gmsgwhile 1:try:r,w,e=select.select([cs,],[],[],0.5)if gmsg:cs.send(send_data(str(raddr)+':'+gmsg))gmsg=Noneif cs in r:msg=cs.recv(8*1024)if msg:data=parse_data(msg)if data!='close':gmsg=dataprint '%s:%s'%(raddr,data)cs.send(send_data(str(raddr)+':'+data))else:breakexcept: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.οnbefοreunlοad=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 οnlοad="init()"><h3>WebSocket</h3><br><br><div id="log"></div><input id="msg" type="textbox" οnkeypress="onkey(event)"/><button οnclick="send()">發送</button>
</body></html>

  

?

?

轉載于:https://www.cnblogs.com/Yeah-come-on/p/3593506.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/273833.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/273833.shtml
英文地址,請注明出處:http://en.pswp.cn/news/273833.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python進階(第三章1) 字典

文章目錄3.1 泛映射類型什么是可散列的數據類型&#xff08;鍵的要求&#xff09;字典的構造方法3.2 字典推導(dictcomp)3.3 常見的映射方法用setdefault處理找不到的鍵3.4 映射的彈性鍵查詢3.4.1 defaultdict:處理找不到的鍵的一個選擇注意&#xff1a;defaultdict與dict實例化…

python基礎 list和tuple

文章目錄一、list1、len()函數可以獲得list元素的個數2、索引從0開始3、末尾追加 append(xx)4、也可以把元素插入到指定的位置&#xff0c;比如索引號為1的位置(insert)5、末尾刪除pop() &#xff0c;并且返回該值6、要刪除指定位置的元素&#xff0c;用pop(i)方法&#xff0c;…

HDU 2818 Building Block

題目連接 http://acm.hdu.edu.cn/showproblem.php?pid2818 題意:給定N個blocks&#xff0c;分在N個堆里&#xff0c;然后又P個操作&#xff0c;每次將x所在的堆放在y所在的堆上&#xff0c;或者詢問x的下面有幾個blocks 做法&#xff1a;帶權并查集 因為要查詢x的下面有多少bl…

百度社會化分享組件使用問題

今天下午玩了玩百度的社會化分享sdk,我是在這下載的sdk http://developer.baidu.com/frontia/sdk 誰知道這個下載鏈接是沒更新的,還是1.0版本的,是尼瑪13年初的版本 搗鼓了半天各種bug 然后去百度官網重新找http://developer.baidu.com/wiki/index.php?titledocs/frontia/res…

python基礎 dict和set

文章目錄dictset4.用集合為列表去重5.集合的增 add,update6.集合的刪 discard,remove,pop,clear7 集合運算7.1 子集(<或者issubset()方法)7.2并集(|或者union()方法)7.3 交集(&或者intersection())7.4 差集(-或者difference()方法)7.5 對稱集(^或者symmetric_difference…

python進階(第三章2)字典和集合

文章目錄3.8 集合論nee中的元素在haystack中出現的次數&#xff0c;可以在任何可迭代對象上3.8.1集合字面量3.8.2 集合推導3.8.3 集合操作3.9 dict和set的背后3.9.1 一個關于效率的實驗3.9.2 字典中的散列表1.散列值和相等性2.散列表算法獲取值&#xff1a;添加新的元素更新現有…

Android下實現GPS定位服務

1.申請Google API Key&#xff0c;參考前面文章 2.實現GPS的功能需要使用模擬器進行經緯度的模擬設置&#xff0c;請參考前一篇文章進行設置 3.創建一個Build Target為Google APIs的項目 4.修改Androidmanifest文件&#xff1a; view plain<uses-library android:name"…

python 鏈表 【測試題】

文章目錄注意&#xff1a;實例講解1 .鏈表基本功能2. 根據值刪除鏈表中的節點信息答案&#xff1a;3.反轉一個單鏈表信息答案4.合并兩個有序鏈表信息答案5.刪除排序鏈表中的重復元素信息答案6.移除鏈表元素信息7.環形鏈表信息進階思路答案注意&#xff1a; 這里的head是只存儲…

WebService應用一例,帶有安全驗證

1、創建WEB項目&#xff0c;添加WEB服務WebService1.asmx&#xff0c;代碼如下&#xff1a; 1 using System;2 using System.Collections.Generic;3 using System.Linq;4 using System.Web;5 using System.Web.Services;6 7 namespace WebService8 {9 /// <summary> …

linux集成開發環境

Linux操作系統的種種集成開發環境隨著Linux的逐漸興起&#xff0c;已經有為數眾多的程序在上面馳騁了&#xff0c;許多開發環境(Development Environment)也應運而生。好的開發環境一定是集成了編輯、編譯和調試等多項功能并且易于使用。本文介紹了一些在Linux上流行的開發環境…

mysql技術內幕《讀書筆記》

文章目錄1. mysql 體系結構和存儲引擎1.5 連接mysql1.5.11. mysql 體系結構和存儲引擎 1.5 連接mysql 連接mysql操作是一個連接進程和mysql數據庫實例進行通信。 本質是進程通信&#xff0c;常用的進程通信方式有管道&#xff0c;命名管道&#xff0c;命名字&#xff0c;TCP/…

DEDECMS全版本gotopage變量XSS ROOTKIT 0DAY

影響版本&#xff1a; DEDECMS全版本 漏洞描敘&#xff1a; DEDECMS后臺登陸模板中的gotopage變量未效驗傳入數據&#xff0c;導致XSS漏洞。 \dede\templets\login.htm 65行左右 <input type"hidden" name"gotopage" value"<?php if(!empty($g…

Android開源庫loopj的android-async-http的 JsonHttpResponseHandler 存在死循環GC_CONCURRENT

我現在用的是 AndroidAsyncHttp 1.4.4 版本&#xff0c;之前遇到一個很奇怪的問題&#xff0c; 當使用 JsonHttpResponseHandler 解析請求的頁面出現服務器錯誤或其他情況返回的內容不是 JSON 字符串時不會調用自己復寫實現的 onSuccess 或者 onFailure 方法&#xff0c;將會出…

python【進階】4.文本和字節序列

文章目錄1. 字符、碼位和字節表述4.1字符問題2. bytes、bytearray 和 memoryview 等二進制序列的獨特特性3. 全部 Unicode 和陳舊字符集的編解碼器4.避免和處理編碼錯誤5.處理文本文件的最佳實踐6.默認編碼的陷阱和標準 I/O 的問題7.規范化 Unicode 文本,進行安全的比較8.規范化…

C#序列化和反序列化

序列化和反序列化我們可能經常會聽到&#xff0c;其實通俗一點的解釋&#xff0c;序列化就是把一個對象保存到一個文件或數據庫字段中去&#xff0c;反序列化就是在適當的時候把這個文件再轉化成原來的對象使用。我想最主要的作用有&#xff1a; 1、在進程下次啟動時讀取上次保…

python【進階】5.一等函數(注銷)

在 Python 中,函數是一等對象。編程語言理論家把“一等對象”定義為滿足下述條件的程 序實體: 在運行時創建能賦值給變量或數據結構中的元素能作為參數傳給函數能作為函數的返回結果 在 Python 中,所有函數都是一等對象。 5.1 把函數視作對象 >>> def d(n): ... …

進程狀態轉換(了解)

進程三個基本狀態&#xff1a;就緒、阻塞、運行 這個比較簡單&#xff0c;進程創建后進入就緒狀態、然后若CPU空閑或能打斷CPU正在執行的進程&#xff08;優先級低的&#xff09;&#xff0c;那么就緒狀態轉換成運行態&#xff0c;運行時&#xff0c;進程需要用到其他資源&…

rebuild online意外終止導致ora-8104錯誤的實驗

rebuild online意外終止導致ora-8104錯誤的實驗 SQL> !oerr ora 810408104, 00000, "this index object %s is being online built or rebuilt"// *Cause: the index is being created or rebuild or waited for recovering // from the online (re)build // *Act…

關于range方法,如果你覺得python很簡單就錯了

前言&#xff1a;在系統學習迭代器之前&#xff0c;我一直以為 range() 方法也是用于生成迭代器的&#xff0c;現在卻突然發現&#xff0c;它生成的只是可迭代對象&#xff0c;而并不是迭代器&#xff01; 1、range() 是什么&#xff1f; 對于 range() 函數&#xff0c;有幾個注…

centos下crontab的使用

1.作用使用crontab命令可以修改crontab配置文件&#xff0c;然后該配置由cron公用程序在適當的時間執行&#xff0c;該命令使用權限是所有用戶。2.格式crontab [-u user] {-l | -r | -e}3.crontab命令選項: -u指定一個用戶, -l列出某個用戶的任務計劃, -r刪除某個用戶的任務, -…