用Python写一个模拟qq聊天小程序的代码实例

时间:2021-05-23

Python 超简单的聊天程序

客户端:

import socket, syshost = '10.248.27.23'# host = raw_input("Plz imput destination IP:")# data = raw_input("Plz imput what you want to submit:")port = 51423s = 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, syshost = ''port = 51423s = 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 Threadfrom 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 = Nonedesip = ""desport = 0def 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()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章