博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python实现的简单点对点(p2p)聊天
阅读量:3949 次
发布时间:2019-05-24

本文共 4661 字,大约阅读时间需要 15 分钟。

                       

点对点聊天首先是基于多线程的网络编程,其次就是将每一个连接都保存为一个具有独一属性的对象并添加到连接列表中,对于每一个连接对象发送过来的信息必须要包含主要的三项内容(from,to,messages),这样当信息发送到服务器之后服务器根据to的连接对象遍历连接列表找到目标对象将信息发送给目标,目标拿到信息后就知道是谁发过来的,然后根据id号码进行回复。。此实现将会继续完善,后续新加功能将会在我个人展现

服务器端实现:

#coding:utf-8'''file:server.pydate:2017/9/10 12:43author:lockeyemail:lockey@123.complatform:win7.x86_64 pycharm python3desc:p2p communication serverside'''import socketserver,jsonimport subprocessconnLst = []##  连接列表,用来保存一个连接的信息(代号 地址和端口 连接对象)class Connector(object):#连接对象类    def __init__(self,account,password,addrPort,conObj):        self.account = account        self.password = password        self.addrPort = addrPort        self.conObj = conObjclass MyServer(socketserver.BaseRequestHandler):    def handle(self):        print("got connection from",self.client_address)        register = False        while True:            conn = self.request            data = conn.recv(1024)            if not data:                continue            dataobj = json.loads(data.decode('utf-8'))            #如果连接客户端发送过来的信息格式是一个列表且注册标识为False时进行用户注册            if type(dataobj) == list and not register:                account = dataobj[0]                password = dataobj[1]                conObj = Connector(account,password,self.client_address,self.request)                connLst.append(conObj)                register = True                continue            print(connLst)            #如果目标客户端在发送数据给目标客服端            if len(connLst) > 1 and type(dataobj) == dict:                sendok = False                for obj in connLst:                    if dataobj['to'] == obj.account:                        obj.conObj.sendall(data)                        sendok = True                if sendok == False:                    print('no target valid!')            else:                conn.sendall('nobody recevied!'.encode('utf-8'))                continueif __name__ == '__main__':    server = socketserver.ThreadingTCPServer(('192.168.1.4',8022),MyServer)    print('waiting for connection...')    server.serve_forever()  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

客户端实现:

#coding:utf-8'''file:client.py.pydate:2017/9/10 11:01author:lockeyemail:lockey@123.complatform:win7.x86_64 pycharm python3desc:p2p communication clientside'''from socket import *import threading,sys,json,reHOST = '192.168.1.4'  ##PORT=8022BUFSIZ = 1024  ##缓冲区大小  1KADDR = (HOST,PORT)tcpCliSock = socket(AF_INET,SOCK_STREAM)tcpCliSock.connect(ADDR)userAccount = Nonedef register():    myre = r"^[_a-zA-Z]\w{0,}"    #正则验证用户名是否合乎规范    accout = input('Please input your account: ')    if not re.findall(myre, accout):        print('Account illegal!')        return None    password1  = input('Please input your password: ')    password2 = input('Please confirm your password: ')    if not (password1 and password1 == password2):        print('Password not illegal!')        return None    global userAccount    userAccount = accout    return (accout,password1)class inputdata(threading.Thread):    def run(self):        while True:            sendto = input('to>>:')            msg = input('msg>>:')            dataObj = {
'to':sendto,'msg':msg,'froms':userAccount}            datastr = json.dumps(dataObj)            tcpCliSock.send(datastr.encode('utf-8'))class getdata(threading.Thread):    def run(self):        while True:            data = tcpCliSock.recv(BUFSIZ)            dataObj = json.loads(data.decode('utf-8'))            print('{} -> {}'.format(dataObj['froms'],dataObj['msg']))def main():    while True:        regInfo = register()        if  regInfo:            datastr = json.dumps(regInfo)            tcpCliSock.send(datastr.encode('utf-8'))            break    myinputd = inputdata()    mygetdata = getdata()    myinputd.start()    mygetdata.start()    myinputd.join()    mygetdata.join()if __name__ == '__main__':    main()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

运行结果示例:

服务器端结果:

这里写图片描述

客户端1:

这里写图片描述

客户端2:

这里写图片描述

客户端3:

这里写图片描述

如果运行出错请检查平台以及python版本号

           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!

你可能感兴趣的文章
独家 | 大数据下的自杀风险感知与疏导(附视频&PPT下载)
查看>>
鉴别一个人是否 js 入门的标准竟然是?!
查看>>
2017年度盘点:15个最流行的GitHub机器学习项目
查看>>
Python 写各大聊天系统的屏蔽脏话功能原理
查看>>
全世界的AI明星公司都在这!CB人工智能100深度拆解
查看>>
为你分享73篇论文解决深度强化学习的18个关键问题
查看>>
28 款 GitHub 最流行的开源机器学习项目(附地址)
查看>>
从零开始教你训练神经网络(附公式&学习资源)
查看>>
计算机视觉这一年:这是最全的一份CV技术报告
查看>>
推荐9个软件神器,26个网站,让你PPT更加风骚
查看>>
网易云音乐刷了我的过去...
查看>>
物联网产业链全景图及8大环节超详解读
查看>>
快讯丨工信部发布《促进新一代人工智能产业发展三年行动计划(2018-2020年)》
查看>>
微信跳一跳技术手段高分秘籍;竟还可以伪造POST请求刷分
查看>>
【含代码】Python爬虫实战:爬取全站小说排行榜
查看>>
总结过去2017年最受欢迎的十大机器学习Python库
查看>>
恕我直言,你可能被支付宝账单预测关键词骗了!
查看>>
2018年春运火车票今天开售,手把手教你用Python抢票回家过年....
查看>>
【精华】大数据在营销中的6大优势
查看>>
炫!把你的生活轨迹用大数据展示后.......惊呆了~
查看>>