python3实现多线程聊天室
作者:LGX_TvT 时间:2021-09-11 07:35:47
使用python3创建多线程聊天室,供大家参考,具体内容如下
import threading
import socket
#socket
udpSocket = None
#计数器
num = 1
#1.创建接受,发送方法
def inMessage():
global num
while True:
#等待接收消息
data = udpSocket.recvfrom(1024)
#4. 将接收到的数据再发送给对方
udpSocket.sendto(data[0], data[1])
#打印获得的消息
print("\r>> 消息%d => 来自:%s => %s"%(num,data[1],data[0].decode('gb2312')))
print('\r>>',end='')
#消息数量+1
num+=1
def outMessage():
while True:
#发送地址
sendAddr = ('192.168.106.132',8080)
#获得输入数据
senddata = input('\r>>')
#发送消息
udpSocket.sendto(senddata.encode('gb2312'),sendAddr)
#2.使用多线程执行接收发送
def main():
global udpSocket
#创建socket
udpSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#绑定端口
udpSocket.bind(('',8686))
#创建线程
t1 = threading.Thread(target=inMessage)
t2 = threading.Thread(target=outMessage)
#启动线程
t1.start()
t2.start()
#主线程堵塞
t1.join()
t2.join()
#3.主方法运行
if __name__ == "__main__":
main()
效果图:
来源:https://blog.csdn.net/l1336037686/article/details/78735412
标签:python,聊天室
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python安装selenium包详细过程
2023-04-12 00:05:31
![](https://img.aspxhome.com/file/2023/1/72941_0s.png)
详解如何用Python模拟登录淘宝
2023-09-29 19:07:34
![](https://img.aspxhome.com/file/2023/8/61978_0s.jpg)
oracle 存储过程和函数例子
2023-06-26 08:19:30
如何使用表单发送电子邮件?
2010-05-16 15:13:00
laravel学习教程之关联模型
2023-06-11 19:46:55
推荐一篇不错的新手asp编程的基本法则
2011-04-15 11:08:00
数据库名词解释
2008-09-12 17:28:00
Python二叉树定义与遍历方法实例分析
2023-06-26 17:26:56
加密处理使密码更安全[CFS编码加密]
2008-03-19 13:30:00
SQL Server从安装到建库为新手寻找捷径
2009-01-13 13:22:00
MySQL数据库数据备份和恢复详解
2009-07-15 10:51:00
php数组索引与键值操作技巧实例分析
2023-07-01 21:39:10
显示某日期所在星期的所有日期asp代码
2008-06-01 16:05:00
响应浏览器地址栏#(hash/fragment)变化
2009-12-28 10:45:00
CSS实现垂直居中的5种方法
2009-03-04 12:53:00
![](https://img.aspxhome.com/file/UploadPic/20093/4/0613598e4-88s.jpg)
PHP实现克鲁斯卡尔算法实例解析
2023-09-08 19:35:57
关于VSCode 配置使用 PyLint 语法检查器的问题
2023-06-18 17:10:33
![](https://img.aspxhome.com/file/2023/0/61430_0s.png)
Python栈的实现方法示例【列表、单链表】
2023-07-20 15:51:42
Python学习小技巧总结
2021-09-21 09:28:49
Python实现将mp3音频格式转换为wav格式
2023-09-18 15:50:02
![](https://img.aspxhome.com/file/2023/7/62557_0s.png)