python实现的简单点对点(p2p)聊天
点对点聊天首先是基于多线程的网络编程,其次就是将每一个连接都保存为一个具有独一属性的对象并添加到连接列表中,对于每一个连接对象发送过来的信息必须要包含主要的三项内容(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)聊天的更多相关文章
- python实现一个简单的网络聊天程序
一.Linux Socket 1.Linux Socke基本上就是BSD Socket(伯克利套接字) 伯克利套接字的应用编程接口(API)是采用C语言的进程间通信的库,经常用在计算机网络间的通信.B ...
- python socket编程 实现简单p2p聊天程序
目标是写一个python的p2p聊天的项目,这里先说一下python socket的基础课程 一.Python Socket 基础课程 Socket就是套接字,作为BSD UNIX的进程通信机制,取后 ...
- 通过python 构建一个简单的聊天服务器
构建一个 Python 聊天服务器 一个简单的聊天服务器 现在您已经了解了 Python 中基本的网络 API:接下来可以在一个简单的应用程序中应用这些知识了.在本节中,将构建一个简单的聊天服务器.使 ...
- Python练习3-XML-RPC实现简单的P2P文件共享
XML-RPC实现简单的P2P文件共享 先来个百度百科: XML-RPC的全称是XML Remote Procedure Call,即XML(标准通用标记语言下的一个子集)远程过程调用.它是一套允许运 ...
- python 全栈开发,Day130(多玩具端的遥控功能, 简单的双向聊天,聊天记录存放数据库,消息提醒,玩具主动发起消息,玩具主动发起点播)
先下载github代码,下面的操作,都是基于这个版本来的! https://github.com/987334176/Intelligent_toy/archive/v1.3.zip 注意:由于涉及到 ...
- 百行go代码构建p2p聊天室
百行go代码构建p2p聊天室 百行go代码构建p2p聊天室 1. 上手使用 2. whisper 原理 3. 源码解读 3.1 参数说明 3.1 连接主节点 3.2 我的标识 3.2 配置我的节点 3 ...
- 以太坊系列之十八: 百行go代码构建p2p聊天室
百行go代码构建p2p聊天室 百行go代码构建p2p聊天室 1. 上手使用 2. whisper 原理 3. 源码解读 3.1 参数说明 3.1 连接主节点 3.2 我的标识 3.2 配置我的节点 3 ...
- python之pandas简单介绍及使用(一)
python之pandas简单介绍及使用(一) 一. Pandas简介1.Python Data Analysis Library 或 pandas 是基于NumPy 的一种工具,该工具是为了解决数据 ...
- 使用Servlet和JSP实现一个简单的Web聊天室系统
1 问题描述 利用Java EE相关技术实现一个简单的Web聊天室系统,具体要求如下. (1)编写一个登录 ...
随机推荐
- 创建属性Attribute
XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlPath); var root = xmlDoc.DocumentElement;//取到 ...
- Echarts 简单报表系列二:折线图
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- [codechef July Challenge 2017] Chef and Sign Sequences
CHEFSIGN: 大厨与符号序列题目描述大厨昨天捡到了一个奇怪的字符串 s,这是一个仅包含‘<’.‘=’和‘>’三种比较符号的字符串.记字符串长度为 N,大厨想要在字符串的开头.结尾,和 ...
- Javascript 将 HTML 页面生成 PDF 并下载
最近碰到个需求,需要把当前页面生成 pdf,并下载.弄了几天,自己整理整理,记录下来,我觉得应该会有人需要 :) html2canvas 简介 我们可以直接在浏览器端使用html2canvas,对整个 ...
- 解决 TCP_socket 粘包问题
所谓粘包问题主要还是C/S两端数据传输时 因为接收方不知道消息之间的界限,不知道一次性提取多少字节的数据所造成的 根本原因:粘包是由TCP协议本身造成的,TCP为提高传输效率,发送方往往要收集到足够多 ...
- windows 下的常用工具
网址:http://cmder.net/ 如果vim乱码 命令行输入 set LC_ALL=zh_CN.UTF8 添加cmder到鼠标右键 c://安装目录/Cmder.exe /REGISTE ...
- angular 常用插件集合
md5加密 https://www.npmjs.com/package/md5-typescript angular echarts https://github.com/xieziyu/ng ...
- laravel本地开发的项目部署到服务器上
不建议用ftp,建议用git.svn等工具从你的开发服务器上拉取.或者使用一些自动构建发布的工具.如果非要用ftp上传,建议用以下步骤: 服务器上安装composer,并使用`composer sel ...
- Win10系列:UWP界面布局基础8
路由事件 XAML不仅继承了传统的事件处理方式,还引入了一个增强型事件处理机制:路由事件(RoutedEvent).路由事件和传统事件的不同是:路由事件允许一个对象触发事件后,可以同时拥有多个事件接收 ...
- 阿里云免费申请https证书
申请地址 https://common-buy.aliyun.com/?spm=a2c4e.11153940.blogcont65199.22.30f968210RsUSx&commodi ...