python开发实例之python使用Websocket库开发简单聊天工具实例详解(python+Websocket+JS)

所属分类: 脚本专栏 / python 阅读数: 258
收藏 0 赞 0 分享

最近又回顾了下Websocket,发现已经忘的七七八八了。于是用js写了客户端,用python写了服务端,来复习一下这方面的知识。

先看一下python简单聊天工具最终效果

一个客户端连上服务的并发送消息

另一个客户端连上服务的并发送消息

服务的收到客户端的全部消息并返回消息

一个客户端掉线并不影响其它socket连接

列取全部连接客户端对象和当前发消息的客户端对象

先安装websockets

pip install websockets

python简单聊天工具实例源码

Python聊天工具服务端

#! -*- coding: utf-8 -*-
"""
Info: Websocket 的使用示例
"""
import asyncio
import websockets

websocket_users = set()


# 检测客户端权限,用户名密码通过才能退出循环
async def check_user_permit(websocket):
  print("new websocket_users:", websocket)
  websocket_users.add(websocket)
  print("websocket_users list:", websocket_users)
  while True:
    recv_str = await websocket.recv()
    cred_dict = recv_str.split(":")
    if cred_dict[0] == "admin" and cred_dict[1] == "123456":
      response_str = "Congratulation, you have connect with server..."
      await websocket.send(response_str)
      print("Password is ok...")
      return True
    else:
      response_str = "Sorry, please input the username or password..."
      print("Password is wrong...")
      await websocket.send(response_str)


# 接收客户端消息并处理,这里只是简单把客户端发来的返回回去
async def recv_user_msg(websocket):
  while True:
    recv_text = await websocket.recv()
    print("recv_text:", websocket.pong, recv_text)
    response_text = f"Server return: {recv_text}"
    print("response_text:", response_text)
    await websocket.send(response_text)


# 服务器端主逻辑
async def run(websocket, path):
  while True:
    try:
      await check_user_permit(websocket)
      await recv_user_msg(websocket)
    except websockets.ConnectionClosed:
      print("ConnectionClosed...", path)  # 链接断开
      print("websocket_users old:", websocket_users)
      websocket_users.remove(websocket)
      print("websocket_users new:", websocket_users)
      break
    except websockets.InvalidState:
      print("InvalidState...")  # 无效状态
      break
    except Exception as e:
      print("Exception:", e)


if __name__ == '__main__':
  print("127.0.0.1:8181 websocket...")
  asyncio.get_event_loop().run_until_complete(websockets.serve(run, "127.0.0.1", 8181))
  asyncio.get_event_loop().run_forever()

python简单聊天工具客户端代码Html+Js

<!-- Websocket 的使用示例 -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>测试Socket——ws://127.0.0.1:8181</title>
  <script>
    var socket;
    if ("WebSocket" in window) {
      var ws = new WebSocket("ws://127.0.0.1:8181/test");
      socket = ws;
      ws.onopen = function() {
        console.log('连接成功');
        alert("连接成功, 请输入账号和密码");
      };
      ws.onmessage = function(evt) {
        var received_msg = evt.data;
        document.getElementById("showMes").value+=received_msg+"\n";
      };
      ws.onclose = function() {
        alert("断开了连接");
      };
    } else {
      alert("浏览器不支持WebSocket");
    }
    function sendMeg(){
      var message=document.getElementById("name").value+":"+document.getElementById("mes").value;
      document.getElementById("showMes").value+=message+"\n\n";
      socket.send(message);
    }
  </script>
</head>
<body>
  <textarea rows="3" cols="30" id="showMes" style="width:300px;height:500px;"></textarea>
  <br/>
  <label>名称</label>
  <input type="text" id="name"/>
  <br/>
  <label>消息</label>
  <input type="text" id="mes"/>
  <button onclick="sendMeg();">发送</button>
</body>
</html>

本文主要介绍了python使用Websocket库开发简单聊天工具实例详细,更多关于python Websocket库开发知识请查看下面的相关链接

更多精彩内容其他人还在看

pandas的qcut()方法详解

这篇文章主要介绍了pandas的qcut()方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

从列表或字典创建Pandas的DataFrame对象的方法

这篇文章主要介绍了从列表或字典创建Pandas的DataFrame对象的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas.DataFrame的pivot()和unstack()实现行转列

这篇文章主要介绍了pandas.DataFrame的pivot()和unstack()实现行转列,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

pandas中的series数据类型详解

这篇文章主要介绍了pandas中的series数据类型详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas 时间格式转换的实现

这篇文章主要介绍了pandas 时间格式转换的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

python中时间、日期、时间戳的转换的实现方法

这篇文章主要介绍了python中时间、日期、时间戳的转换的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

pandas进行时间数据的转换和计算时间差并提取年月日

这篇文章主要介绍了pandas进行时间数据的转换和计算时间差并提取年月日,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法

这篇文章主要介绍了详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

python和c语言的主要区别总结

在本篇文章里小编给各位整理了关于python和c语言的主要区别的相关知识帖内容,有需要的朋友们学习阅读下。
收藏 0 赞 0 分享

选择Python写网络爬虫的优势和理由

在本篇文章里小编给各位整理了一篇关于选择Python写网络爬虫的优势和理由以及相关代码实例,有兴趣的朋友们阅读下吧。
收藏 0 赞 0 分享
查看更多