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

服务器端实现:

#coding:utf-8
'''
file:server.py
date:2017/9/10 12:43
author:lockey
email:lockey@123.com
platform:win7.x86_64 pycharm python3
desc:p2p communication serverside
'''
import socketserver,json
import subprocess connLst = []
## 连接列表,用来保存一个连接的信息(代号 地址和端口 连接对象)
class Connector(object):#连接对象类
def __init__(self,account,password,addrPort,conObj):
self.account = account
self.password = password
self.addrPort = addrPort
self.conObj = conObj class 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'))
continue if __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.py
date:2017/9/10 11:01
author:lockey
email:lockey@123.com
platform:win7.x86_64 pycharm python3
desc:p2p communication clientside
'''
from socket import *
import threading,sys,json,re HOST = '192.168.1.4' ##
PORT=8022
BUFSIZ = 1024 ##缓冲区大小 1K
ADDR = (HOST,PORT) tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
userAccount = None
def 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版本号

python实现的简单点对点(p2p)聊天的更多相关文章

  1. python实现一个简单的网络聊天程序

    一.Linux Socket 1.Linux Socke基本上就是BSD Socket(伯克利套接字) 伯克利套接字的应用编程接口(API)是采用C语言的进程间通信的库,经常用在计算机网络间的通信.B ...

  2. python socket编程 实现简单p2p聊天程序

    目标是写一个python的p2p聊天的项目,这里先说一下python socket的基础课程 一.Python Socket 基础课程 Socket就是套接字,作为BSD UNIX的进程通信机制,取后 ...

  3. 通过python 构建一个简单的聊天服务器

    构建一个 Python 聊天服务器 一个简单的聊天服务器 现在您已经了解了 Python 中基本的网络 API:接下来可以在一个简单的应用程序中应用这些知识了.在本节中,将构建一个简单的聊天服务器.使 ...

  4. Python练习3-XML-RPC实现简单的P2P文件共享

    XML-RPC实现简单的P2P文件共享 先来个百度百科: XML-RPC的全称是XML Remote Procedure Call,即XML(标准通用标记语言下的一个子集)远程过程调用.它是一套允许运 ...

  5. python 全栈开发,Day130(多玩具端的遥控功能, 简单的双向聊天,聊天记录存放数据库,消息提醒,玩具主动发起消息,玩具主动发起点播)

    先下载github代码,下面的操作,都是基于这个版本来的! https://github.com/987334176/Intelligent_toy/archive/v1.3.zip 注意:由于涉及到 ...

  6. 百行go代码构建p2p聊天室

    百行go代码构建p2p聊天室 百行go代码构建p2p聊天室 1. 上手使用 2. whisper 原理 3. 源码解读 3.1 参数说明 3.1 连接主节点 3.2 我的标识 3.2 配置我的节点 3 ...

  7. 以太坊系列之十八: 百行go代码构建p2p聊天室

    百行go代码构建p2p聊天室 百行go代码构建p2p聊天室 1. 上手使用 2. whisper 原理 3. 源码解读 3.1 参数说明 3.1 连接主节点 3.2 我的标识 3.2 配置我的节点 3 ...

  8. python之pandas简单介绍及使用(一)

    python之pandas简单介绍及使用(一) 一. Pandas简介1.Python Data Analysis Library 或 pandas 是基于NumPy 的一种工具,该工具是为了解决数据 ...

  9. 使用Servlet和JSP实现一个简单的Web聊天室系统

    1 问题描述                                                利用Java EE相关技术实现一个简单的Web聊天室系统,具体要求如下. (1)编写一个登录 ...

随机推荐

  1. Python图片缩放

    from PIL import Image def size(jpg,now_size): im = Image.open(jpg) width, height = im.size if width& ...

  2. fastjson如何指定字段不序列化

    fastjson是一款由阿里巴巴提供的性能出色的json序列化与反序列化库,而且使用很方便,我们可以使用JSON.toJSONString(object)将一个对象序列化为json格式,但是如果我们不 ...

  3. python中eval()和json.dumps的使用

    在python中通过requests.get(url)获取json数据,此时可能需要eval进行解析. # -*- coding: utf-8 -*- import requests r = requ ...

  4. PyCharm+Qt Designer+PyUIC安装配置教程

    Qt Designer用于像VC++的MFC一样拖放.设计控件 PyUIC用于将Qt Designer生成的.ui文件转换成.py文件 Qt Designer和PyUIC都包含在PyQt5中,所以我们 ...

  5. angular组件之间的通讯

    组件通讯,意在不同的指令和组件之间共享信息.如何在两个多个组件之间共享信息呢. 最近在项目上,组件跟组件之间可能是父子关系,兄弟关系,爷孙关系都有.....我也找找了很多关于组件之间通讯的方法,不同的 ...

  6. OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/django'

    http://blog.csdn.net/qq_34078897/article/details/50821553 权限问题,sudo

  7. 未来Linux系统将是运维行业必备的技能之一

    关于linux,这个并不是每个人都能用或者需要用的,因为平时有很多人用电脑只是为了上上网,聊聊天,打打游戏,这个是完全不需要用linux的.关于linux,是不能用正常的大家所熟知的window来认知 ...

  8. 快递小哥逆袭自传:用了6年时间做到了IT部门主管

    在我30岁生日那天,终于收到升职的通知,自己如愿的也从一名小小程序员升职成为IT主管,负责公司硬件设备驱动程序开发项目,工资也从原来月薪10K变到现在月薪20K.或许对于很多人而言,在三十岁的时候,可 ...

  9. bzoj1238

    题解: 傻逼模拟题 果断的复制了题解(还没有c++题解?) 代码: program p2509; type arr=array[..] of boolean; var tot:longint; s:a ...

  10. windows7环境下java jdk的配置

    第一步: 肯定是先下载好java jdk啦~~ 网址在这里:http://www.oracle.com/technetwork/java/javase/downloads/index.html 打开这 ...