其他的不说,原理自己搜下,直接上代码

客户端代码:

<html>
<head>
<title>WebSocket</title><script src="jquery路径" type="text/javascript"></script><style>*{font-family: "微软雅黑"; margin: 0; padding: 0;}html,
body{width: 100%; height: 100%; background: #000; position: relative;}.msgInfo{position: fixed; right: 2%; top: 2%; height: 96%; width: 20%; background: #666;}
.msgInfo .hd{width: 100%; text-align: center; height: 40px; line-height: 40px; color: #fff; background: #333;}
.msgInfo .bd{ padding: 20px; height: 100%; overflow: auto; color: #fff; line-height: 30px;}
.msgInfo .bd p{margin: 5px 0;}.sendBox{position: fixed; left: 2%; bottom: 2%; width: 74%; height: 10%; background: #666; overflow: hidden;}
.sendBox textarea{width: 90%; height: 100%; display: inline-block; background: #666; color: #fff; border: none; float: left;}
.sendBox button{width: 10%; height: 100%; display: inline-block; background: #333; cursor: pointer; color: #fff; border: none; float: left;}.renBox{margin-left: 2%; margin-top: 2%; width: 74%; height: 84%; position: relative; overflow: hidden; float: left;}
.renBox .ren{display: inline-block; position: absolute; left: 500px; top: 500px;}
.renBox .ren .renHead{ display: inline-block; width: 20px; height: 20px; border-radius: 10px; background: #fff;}
.renBox .ren .sayInfo{color: #fff; position: absolute; top: -30px; width: 200px; left: -90px; text-align: center;}
.renBox div{color: #fff; margin-left: 100%; width: 100%; overflow: hidden; height: 30px;line-height: 30px; font-size: 20px;}.firstStep{position: fixed; width: 100%; height: 100%; z-index: 999; background: #000; text-align: center;}
.firstStep .firstName{display: inline-block; padding-top: 300px;}
.firstStep .firstName .username{width: 300px; height: 40px; border: 0; padding: 0 10px;}
.firstStep .firstName .btn{width: 100px; height: 40px; border: 0; background: #333; color: #fff; cursor: pointer;}</style>
<script>
var socket;  function init(username){var host = "ws://localhost:11011/name/"+username;try{  socket = new WebSocket(host);  socket.onopen    = function(msg){log('您已经进入聊天室')};socket.onmessage = function(msg){log(msg.data);};socket.onclose   = function(msg){log("与服务器连接断开");};}catch(ex){log(ex);}$(".sendInfo").focus();
}  function send(){  var txt,msg;  txt = $(".sendInfo");msg = txt.val();if(!msg){alert("Message can not be empty");return;}txt.val('');txt.focus();  try{socket.send(msg);$('.sayInfo').html(msg)
//        log("我说:"+msg);} catch(ex){log(ex);}
}  window.οnbefοreunlοad=function(){  try{  socket.send('quit');  socket.close();  socket=null;  }  catch(ex){  log(ex);  }
};  function nameok(){var _name = $('input[name="username"]').val();if(!_name){alert('请给自己取个名字吧')}else{$('.firstStep').remove()init(_name)}
}function log(msg){$('.msgInfo .bd').append('<p>'+ msg +'</p>');//动画var _html = $('<div>',{'class':'showMsg'});_html.html(msg);$('.renBox').append(_html);_html.animate({'marginLeft':'-100%'}, 10000, function(){_html.remove()})
}
function show(obj){obj.fadeIn()
}
function onkey(event){ if(event.keyCode==13){ send(); } }
</script>
<link href="/static/css/css.css" type="text/css" rel="stylesheet" />
</head>  <body>
<div class="renBox"><!--<div class="ren">--><!--<span class="sayInfo"></span>--><!--<span class="renHead"></span>--><!--</div>-->
</div>
<div class="msgInfo"><div class="hd">聊天记录</div><div class="bd"></div>
</div>
<div class="sendBox"><textarea class="sendInfo"></textarea><button οnclick="send()">发送</button>
</div>
</body>
<div class="firstStep"><div class="firstName"><input type="text" class="username" name="username" placeholder="给自己取一个响亮的名字!" /><input type="button" class="btn" οnclick="nameok()" value="进入聊天" /></div>
</div>
</html>  

服务端代码

# coding: utf-8from socket import *
import json, time, threading
config = {'HOST': 'localhost','PORT': 11011,'LISTEN_CLIENT': 50,'KEY': '391f10fadc339e9ec5fa15af60030ac1','SIZE': 2048,'TIME_OUT': 1000,'HEART_TIME': 5,'MAGIC_STRING': '258EAFA5-E914-47DA-95CA-C5AB0DC85B11','HANDSHAKE_STRING': "HTTP/1.1 101 Switching Protocols\r\n" \"Upgrade:websocket\r\n" \"Connection: Upgrade\r\n" \"Sec-WebSocket-Accept: {1}\r\n" \"WebSocket-Location: ws://{2}/chat\r\n" \"WebSocket-Protocol:chat\r\n\r\n"
}class Server():"""服务端基类"""def __init__(self):self.sock = socket(AF_INET, SOCK_STREAM)self.sock.bind((config['HOST'], config['PORT']))  # 监听端口self.sock.listen(config['LISTEN_CLIENT'])  # 监听客户端数量# 所有监听的客户端self.clients = {}self.thrs = {}self.users = {}self.stops = []# 监听客户端连接def listen_client(self):while 1:# 循环监听tcpClientSock, addr = self.sock.accept()address = addr[0] + ':' + str(addr[1])  # ip:port# 握手topInfo = tcpClientSock.recv(1024)headers = {}if not topInfo:tcpClientSock.close()continueheader, data = topInfo.split('\r\n\r\n', 1)try:getInfo = header.split('\r\n')[0].split(' ')[1].split('/')[1:]if getInfo[0] == 'name':self.users[address] = str(getInfo[1])else:self.users[address] = '匿名用户'except:self.users[address] = '匿名用户'for line in header.split('\r\n')[1:]:key, val = line.split(': ', 1)headers[key] = valif 'Sec-WebSocket-Key' not in headers:tcpClientSock.close()continueimport hashlib, base64sec_key = headers['Sec-WebSocket-Key']res_key = base64.b64encode(hashlib.sha1(sec_key + config['MAGIC_STRING']).digest())str_handshake = config['HANDSHAKE_STRING'].replace('{1}', res_key).replace('{2}', config['HOST'] + ':' + str(config['PORT']))tcpClientSock.send(str_handshake)# 握手成功 分配线程进行监听print(address+'进来了')self.clients[address] = tcpClientSockself.thrs[address] = threading.Thread(target=self.readMsg, args=[address])self.thrs[address].start()# print(self.clients)def readMsg(self, address):# print(self.clients)if address not in self.clients:return Falseclient = self.clients[address]import selecttime_out = 0while 1:# print(len(self.clients))if address in self.stops:self.close_client(address)print(address + u'已经离开了系统!')break# 检测超时if time_out >= config['TIME_OUT']:self.close_client(address)breaktime_out += 5infds, outfds, errfds = select.select([client, ], [], [], 5)if len(infds) == 0:continuetime_out = 0try:info = client.recv(1024)except:self.close_client(address)breakif not info:continueif info == 'quit':self.close_client(address)breakcode_len = ord(info[1]) & 127if code_len == 126:masks = info[4:8]data = info[8:]elif code_len == 127:masks = info[10:14]data = info[14:]else:masks = info[2:6]data = info[6:]i = 0raw_str = ""for d in data:# print(masks, masks[i % 4])raw_str += chr(ord(d) ^ ord(masks[i % 4]))# print(raw_str)i += 1# 获取到输入的数据 向所有的客户端发送# 开启线程记录if raw_str:t1 = threading.Thread(target=self.send_data, args=[raw_str, address])t1.start()def send_data(self, data, address):import structfrom urllib import unquotetry:username = unquote(self.users[address])except:username = '匿名用户'if data:data = str('【'+username+'说】'+data)else:return Falsetoken = "\x81"length = len(data)if length < 126:token += struct.pack("B", length)elif length <= 0xFFFF:token += struct.pack("!BH", 126, length)else:token += struct.pack("!BQ", 127, length)# struct为Python中处理二进制数的模块,二进制流为C,或网络流的形式。data = '%s%s' % (token, data)try:for key, val in self.clients.iteritems():client = valtry:client.send(data)except:self.close_client(key)except:passdef close_client(self, address):try:client = self.clients.pop(address)self.stops.append(address)client.close()del self.users[address]except:passprint(address+u'已经退出')if __name__ == '__main__':c = Server()c.listen_client()

用Python写了个websocket即时聊天网页(含客户端、服务端代码)相关推荐

  1. java xmpp协议_GitHub - zhengzhi530/xmpp: 基于Xmpp协议的即时通讯社交软件(客户端+服务端)...

    yyquan 开源一个自己去年写的基于Xmpp协议的即时通讯社交软件 (客户端+服务端) 本项目仅供参考,对于正在学习Xmpp以及javaweb后台的同学,可以看一下. 做这个项目纯属个人兴趣爱好,所 ...

  2. Python用tornado的websocket开发聊天室

    Python用tornado的websocket开发聊天室 用tornado开发基于异步websocket聊天室-demo 目录结构 Python包 main.py app/views.py temp ...

  3. 小成开发日记---利用Qt/C++实现基于Udp协议的网络聊天室(分服务端和客户端的开发【轻聊v1.0.1】)

    作者:小成Charles 原创作品 转载请标注原创文章地址:https://blog.csdn.net/weixin_42999453/article/details/112363393 一.引言 最 ...

  4. winform服务器消息推送,winform项目——仿QQ即时通讯程序12:服务端程序补充及优化...

    原标题:winform项目--仿QQ即时通讯程序12:服务端程序补充及优化 上一篇文章大概完成了服务端程序,今天继续做项目的时候发现还有一些功能没有做,还有几处地方不够完善.不做好就会影响客户端程序的 ...

  5. TCP聊天文件服务器v2.2 - 服务端客户端套接字解决分包/粘包问题 - SocketQueue继承以及减少冗余

    TCP聊天+传输文件服务器服务器套接字v2.2 整个图当封面吧 所有版本记录: v1.0 : TCP聊天服务器套接字|PyQt5+socket(TCP端口映射+端口放行)+logging+Thread ...

  6. 2021最新4合1即时通讯IM源码-服务端+PC+WEB+安卓+IOS完整原生源码

    介绍: 20214合1即时通讯IM源码 服务端+PC+WEB+安卓+IOS完整原生源码 附完整开发文档+视频搭建教程. 注意:此源码亲测可用,他处有小问题,我们已经修复.任何源码,难免有瑕疵,但不影响 ...

  7. Node.js联机游戏——gobang五子棋(客户端+服务端+websocket的双人游戏)

    Node.js联机游戏--gobang五子棋(客户端+服务端+websocket的双人游戏) 五子棋的基本结构 ~·基本画图 ~·判断机制 ~···横向/竖向判断 ~···斜向判断 搭建服务器阶段 ~ ...

  8. python写机器人程序_用Python写的一个多线程机器人聊天程序

    本人是从事php开发的, 近来想通过php实现即时通讯(兼容windows).后来发现实现起来特别麻烦, 就想到python.听说这家伙在什么地方都能发挥作用.所以想用python来做通讯模块...所 ...

  9. 用python写聊天机器人_用Python 写一个机器人陪你聊天(文尾有彩蛋)

    工作一忙,原来秉烛夜谈的好友现在都很少聊天,微信都成了微信群的天下,鲜有微信好友给你发消息,想要主动发却也找不到开题话题,怎么办?用Python写一个机器人陪自己聊聊天吧.以下是源码及解析,小白都看得 ...

最新文章

  1. 关于“INS-40922 Invalid Scan Name – Unresolvable to IP address”
  2. python编程工资-2019年Python就业薪资怎么样?看完你就了解了
  3. linux关于文件夹的知识,Ubuntu 7.10 系统文件夹相关知识
  4. php常用操作数组函数,PHP常见数组函数用法小结
  5. Java中的DatagramPacket与DatagramSocket的初步
  6. 通过 PL/SQL Developer 建表
  7. 一页纸项目管理模板_项目管理职场必备读物!这一次全部送给你!
  8. vba与python相比2019_重大改变!Python 或将取代 VBA 成为 Excel 官方脚本语言
  9. Python 面向对象(中)
  10. 让你的Mac读给你听,还能听写,用来练习英语口语!
  11. java求出遍历二叉树的路径,102. 二叉树的层序遍历
  12. 前端调用websocket的3种不同写法
  13. 小学生计算机考试软件,中小学生准考证制作打印软件
  14. 关于LaTex输入大写罗马字母的命令——\expandafter的理解与\MakeUppercase的使用
  15. IP流量重放与pcap文件格式解析
  16. java 计算经度纬度之间的距离
  17. 解决电脑蓝牙可以连接手机电脑等设备却无法连接到耳机的问题
  18. 好和弦-5-调式和音阶
  19. 985毕业,沪漂10年,月薪4w,我却活得一地鸡毛
  20. 洛谷1456 Monkey King

热门文章

  1. 《机器学习-吴恩达》课程笔记week4
  2. 微信好友误删了怎么恢复?巧用这几招,悄悄加回不尴尬
  3. Django 分页 (PageNumberPagination)
  4. 8-2 MVC(六大思维)
  5. python机器学习决策树算法
  6. TPlinker解读
  7. 个人微信公众号VI升级心路
  8. 政府项目申报流程有哪些?
  9. 因“暂存盘”已满而无法启动PS的解决
  10. 投资理财-持有建设的思考