点对点聊天首先是基于多线程的网络编程,其次就是将每一个连接都保存为一个具有独一属性的对象并添加到连接列表中,对于每一个连接对象发送过来的信息必须要包含主要的三项内容(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. loj#2020. 「AHOI / HNOI2017」礼物

    题意:给定xy数组求 \(\sum_{i=0}^{n-1}(x_i+y_{(i+k)\modn}+c)^2\) 题解:先化简可得 \(n*c^2+2*\sum_{i=0}^{n-1}x_i-y_i+\ ...

  2. poj-1061-exgcd

    青蛙的约会 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 128285   Accepted: 27962 Descript ...

  3. 利用tablespace特性将数据库移动到新磁盘

    目前开发一台EC2的PostgreSQL服务器的磁盘空间已经严重不足,该磁盘非LVM,所以不考虑磁盘扩容方法,研发希望可以分区/data/02对应的/dev/xvdl1磁盘分担部分数据库的数据,这样也 ...

  4. C++ string::size_type

    从逻辑上讲,size()成员函数应该似乎返回整型数值,但事实上,size操作返回是string::size_type类型的值.string类类型和其他许多库类型都定义了一些配套类型(companion ...

  5. [LeetCode] 295. Find Median from Data Stream ☆☆☆☆☆(数据流中获取中位数)

    295. Find Median from Data Stream&数据流中的中位数 295. Find Median from Data Stream https://leetcode.co ...

  6. XAMPP/PHPnow/phpStudy安装使用对比

    一.XAMPP 1.1 下载 下载地址:https://www.apachefriends.org/download.html 1.2 安装 双击下载的安装程序进行安装,界面如下图,都是典型的下一步下 ...

  7. 将16进制unsigned char数组转换成整数

    /** * 将unsigned char数组转换成long long数值 * {0x00 0x00 0x20 0x00}转换之后得到8192 * * @param str 数组 * @param le ...

  8. 把旧系统迁移到.Net Core 2.0 日记 (12) --发布遇到的问题

    1. 开发时是在Mac+MySql, 尝试发布时是在SQL2005+Win 2008 (第一版) 在Startup.cs里,数据库连接要改,分页时netcore默认是用offset关键字分页, 如果用 ...

  9. spring boot cloud

    eclipse spring boot 项目创建 https://www.cnblogs.com/shuaihan/p/8027082.html https://www.cnblogs.com/LUA ...

  10. CAD(布置厨洁具)(尺寸标注)5.12

    "TYTK"打开图库,找到平面厨具和洁具.双击选中的厨具,A可以不停旋转90度.给厨具选取正确的位置.画出灶台线,同理画出卫生间的家具.绘制出洗脸台的平台.浴缸的平台. 尺寸标注: ...