用Python写一个模拟qq聊天小程序的代码实例
作者:wdz306ling 时间:2022-04-01 10:01:42
Python 超简单的聊天程序
客户端:
import socket, sys
host = '10.248.27.23'
# host = raw_input("Plz imput destination IP:")
# data = raw_input("Plz imput what you want to submit:")
port = 51423
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((host, port))
except socket.gaierror, e:
print "Address-related error connecting to server: %s" %e
sys.exit(1)
except socket.error, e:
print "Connection error: %s" %e
sys.exit(1)
while 1:
try:
data = raw_input("I say: ")
s.send(data)
buf = s.recv(1024)
if len(buf):
print "he say: "+buf
except:
print "Dialogue Over"
s.close()
sys.exit(0)
服务器:
import socket, traceback, sys
host = ''
port = 51423
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)
ClientSock, ClientAddr = s.accept()
while 1:
try:
buf = ClientSock.recv(1024)
if len(buf):
print "he say: "+buf
data = raw_input("I say: ")
ClientSock.sendall(data)
except:
print "Dialogue Over"
ClientSock.close()
sys.exit(0)
模拟qq聊天,语言环境:Python3
示例代码:
# 编写一个程序,模拟qq聊天
# 要求:程序可以同时发消息和收消息,发和收的过程中程序不退出
# 思路:使用socket来完成(socket 是全双工模式,可以实现收和发同时进行),定义俩个线程,一个负责发消息、一个负责收消息
from threading import Thread
from socket import *
def rec_data():
while True:
rec_info = udpsocket.recvfrom(1024)
print("\r>>%s:%s" % (rec_info[1], rec_info[0].decode("gb2312")))
print("<<", end="")
def send_date():
while True:
send_mes = input("<<")
udpsocket.sendto(send_mes.encode("gb2312"), (desip, desport))
udpsocket = None
desip = ""
desport = 0
def main():
global udpsocket
global desip
global desport
desip = input("对方IP:")
desport = int(input("对方端口:"))
udpsocket = socket(AF_INET, SOCK_DGRAM)
udpsocket.bind(("", 9001))
tr = Thread(target=rec_data)
ts = Thread(target=send_date)
tr.start()
ts.start()
tr.join()
ts.join()
if __name__ == '__main__':
main()
来源:https://blog.csdn.net/wdz306ling/article/details/86623436
标签:python,qq,聊天,程序
0
投稿
猜你喜欢
python实现进度条的多种实现
2021-03-20 10:39:52
python如何删除文件、目录
2022-02-03 09:28:09
Python关于维卷积的理解
2022-06-05 07:26:21
了解不常见但是实用的Python技巧
2022-10-12 09:07:35
Window环境下MySQL UDF提权
2024-01-21 09:53:01
python统计文本字符串里单词出现频率的方法
2021-11-10 17:38:48
Python实现钉钉发送报警消息的方法
2022-11-18 06:06:44
python之生产者消费者模型实现详解
2021-12-03 14:37:15
Asp编写不再让人讨厌的自动弹出窗口
2007-09-29 12:16:00
原生javascript实现DIV拖拽并计算重复面积
2024-04-29 13:18:17
三大措施设置数据库安全 保障网站安全运营
2008-11-28 14:41:00
Python自定义模块的创建与使用
2021-01-05 20:47:14
详细分析Python垃圾回收机制
2021-04-18 02:43:43
Pytorch可视化之Visdom使用实例
2021-01-05 12:16:13
打败 IE 的葵花宝典:CSS Bug Table
2010-08-03 12:30:00
javascript实现无法关闭的弹框
2024-05-08 09:32:13
基于mysql乐观锁实现秒杀的示例代码
2024-01-18 02:01:41
python语言元素知识点详解
2023-07-30 03:33:08
解决Python print输出不换行没空格的问题
2021-03-21 11:05:57
MySQL服务器 IO 100%的分析与优化方案
2024-01-24 08:34:10