pythonsocket建立多用户通讯(Python socket实现多对多全双工通信的方法)
类别:脚本大全 浏览量:591
时间:2022-03-29 10:50:48 pythonsocket建立多用户通讯
Python socket实现多对多全双工通信的方法服务器:#server.py
|
#!/usr/bin/env python #-*-coding:utf-8-*- import sys import struct #将字符串打包为二进制流进行网络传输 import select # import signal #用于捕获中断信号 import cPickle #将python对象进行序列化:dumps将python对象序列化保存为字符串,loads与之相反 from socket import * HOST = '' def send(channel, * args): #发送数据 buffer = cPickle.dumps(args) value = htonl( len ( buffer )) size = struct.pack( "L" ,value) channel.send(size) channel.send( buffer ) def receive(channel): #接收数据 size = struct.calcsize( "L" ) size = channel.recv(size) try : size = ntohl(struct.unpack( "L" ,size)[ 0 ]) #socket.ntohl(参考:http://blog.csdn.net/tatun/article/details/7194973) except struct.error,e: return '' buf = '' while len (buf) < size: buf + = channel.recv(size - len (buf)) return cPickle.loads(buf)[ 0 ] #恢复python对象 class ChatServer( object ): def __init__( self ,PORT,backlog = 5 ): self .clients = 0 self .clientmap = {} self .outputs = [] #Client会话列表 self .server = socket(AF_INET, SOCK_STREAM) self .server.setsockopt(SOL_SOCKET,SO_REUSEADDR, 1 ) #重用套接字地址 self .server.bind((HOST,PORT)) self .server.listen(backlog) signal.signal(signal.SIGINT, self .signalhandler) #使用signal模块捕获中断操作 SIGINT中断进程(ctrl+c), SIGTERM 终止进程,SIGKILL杀死进程,SIGALRM 闹钟信号 def signalhandler( self ,signum,frame): #中断处理方法 print "Shutting down server ..." for output in self .outputs: output.close() self .server.close() def get_client_name( self ,client): info = self .clientmap[client] host,port,name = info[ 0 ][ 0 ],info[ 0 ][ 1 ],info[ 1 ] return ':' .join((( '@' .join((name,host))), str (port))) def run( self ): inputs = [ self .server] print 'Waiting for connect...' while True : try : readable,writeable,execption = select.select(inputs, self .outputs,[]) except select.error,e: break for sock in readable: if sock = = self .server: #服务器端接收 client,address = self .server.accept() print "Chat server: connected from" ,address self .clients + = 1 cname = receive(client) send(client, str (address[ 0 ])) inputs.append(client) self .clientmap[client] = (address,cname) msg = "(Connected : New Client(%d) from %s)\n" % ( self .clients, self .get_client_name(client)) message = "At present, only one of you is in the chat room!" if self .clients = = 1 : send(client,message) for output in self .outputs: send(output,msg) self .outputs.append(client) #将开始回话的client加入Client回话列表 #elif sock == sys.stdin: #break else : try : data = receive(sock) if data: msg = '[' + self .get_client_name(sock) + '] >> ' + data for output in self .outputs: if output! = sock: send(output,msg) else : self .clients - = 1 sock.close() inputs.remove(sock) self .outputs.remove(sock) msg = '(Now hung up: Client from %s)' % self .get_client_name(sock) message = "At present, only one of you is in the chat room!" for output in self .outputs: send(output,msg) if self .clients = = 1 : send( self .outputs[ 0 ],message) except error,e: inputs.remove(sock) self .outputs.remove(sock) self .server.close() if __name__ = = "__main__" : server = ChatServer( 6004 ) server.run() |
客户端:#client.py
|
#!/usr/bin/env python #-*-coding:utf-8-*- from server import send,receive from socket import * import sys import select import cPickle import struct import signal class ChatClient( object ): def __init__( self ,name): self .name = name self .connected = False self .host = 'localhost' self .port = 6004 try : self .sock = socket(AF_INET,SOCK_STREAM) self .sock.connect(( self .host, self .port)) self .connected = True send( self .sock, self .name) data = receive( self .sock) addr = data except error,e: #socket.serro print 'Failed to connect to chat server' sys.exit( 1 ) def run( self ): while True : try : readable,writeable,exception = select.select([ 0 , self .sock],[],[]) for sock in readable: if sock = = 0 : data = sys.stdin.readline().strip() if data: send( self .sock,data) else : data = receive( self .sock) if not data: print 'Client shutting down.' self .connected = False break else : sys.stdout.write(data + '\n' ) sys.stdout.flush() except KeyboardInterrupt: print 'Client interrupted' self .sock.close() break if __name__ = = "__main__" : name = raw_input ( "Please input login name > " ) client = ChatClient(name) client.run() |
以上这篇Python socket实现多对多全双工通信的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持开心学习网。
原文链接:https://blog.csdn.net/zhidetian/article/details/53470849
您可能感兴趣
- python opencv图像表格处理(Opencv-Python图像透视变换cv2.warpPerspective的示例)
- python条形码识别(python3转换code128条形码的方法)
- python将网站图片本地存储(详解Python下载图片并保存本地的两种方式)
- python编程ide工具(这6款Python IDE&代码编辑器,你都用过吗?)
- python 百度搜索结果(Python模拟百度自动输入搜索功能的实例)
- 用python怎么找工作(利用python如何在前程无忧高效投递简历)
- python继承重写构造函数(Python子类继承父类构造函数详解)
- pythondocx安装教程(Python docx库用法示例分析)
- python使用telnet(python 处理telnet返回的More,以及get想要的那个参数方法)
- python基础教学之125 装饰器简介(python3 property装饰器实现原理与用法示例)
- python豆瓣电影爬虫课程设计报告(详解python 模拟豆瓣登录豆瓣6.0)
- python 正则表达式语法大全(python re库的正则表达式入门学习教程)
- python中怎样使用列表的sort方法(详解python中sort排序使用)
- python字典的key(Python使用dict.fromkeys快速生成一个字典示例)
- python爬虫入门代码(python爬虫基础教程:requests库二代码实例)
- python群聊提示(python-itchat 统计微信群、好友数量,及原始消息数据的实例)
- 巴厘岛旅游攻略(巴厘岛旅游攻略7天多少钱)
- 文莱旅游攻略(文莱旅游攻略介绍)
- 马来西亚旅游攻略(马来西亚旅游攻略自由行攻略)
- 缅甸旅游攻略(缅甸旅游攻略必去景点推荐)
- 《庆余年2》新消息,原班人马,肖战特别出演,这才是最好的安排(庆余年2新消息原班人马)
- 宁夏灵武恐龙化石发现始末(宁夏灵武恐龙化石发现始末)
热门推荐
- JQuery中serialize与serializeArray
- 如何在windows上搭建ftp服务器(Windows Server 2016如何搭建部署FTP服务器)
- php重定向网页(phpStudy V8设置301重定向跳转的实现方法)
- vue验证码怎么用(vue验证码组件使用方法详解)
- vue-websocket 组件教程(Vue+express+Socket实现聊天功能)
- ASP.NET cache缓存的用法
- dedecms获取子目录(详解dedecms利用[field:arcurl/]无法获取文章路径的解决方法)
- javascript如何建立一个静态变量(JavaScript中子函数访问外部变量的3种解决方法)
- html5 canvas 性能(基于html5 canvas做批改作业的小插件)
- dedecms标签怎么用(dedecms列表页上一页下一页翻页单独调用的方法)
排行榜
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9