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爬虫入门代码(python爬虫基础教程:requests库二代码实例)
- python同步钉钉用户(python 调用钉钉机器人的方法)
- python删除列表中的重复元素(Python实现去除列表中重复元素的方法总结7种方法)
- 怎么python爬取网页图片(详解Python静态网页爬取获取高清壁纸)
- python mongodb 基本操作(Python使用pymongo库操作MongoDB数据库的方法实例)
- python实例教程(Python魔法方法详解)
- python中if的条件语句(浅谈Python的条件判断语句if/else语句)
- python钉钉机器人(python钉钉机器人运维脚本监控实例)
- python如何用md5作为文档名(Python生成MD5值的两种方法实例分析)
- 虚拟环境python详细教程(python创造虚拟环境方法总结)
- python使用教程操作(详解python中@的用法)
- python format的用法(Python中format格式输出全解)
- python numpy矩阵详解(基于Numpy.convolve使用Python实现滑动平均滤波的思路详解)
- python接口自动化接口依赖(python接口自动化十六--参数关联接口后传详解)
- python复杂的验证码处理(Python 通过打码平台实现验证码的实现)
- python面向对象的介绍(Python面向对象思想与应用入门教程类与对象)
- 九月初,爱如蜜糖,甜到心扉,迷恋彼此,一日不见兮,思之若狂(九月初爱如蜜糖)
- ()
- 对你思念入骨的女人,跟你见面时会有这几种表现,藏都藏不住(对你思念入骨的女人)
- 纳兰性德绝美作,一场重逢,成就最后一首称得上惊艳的《如梦令》(纳兰性德绝美作)
- 如何快速赚钱(如何快速赚钱方法真实有效)
- 这里输入关键词(如何输入关键词)
热门推荐
- sqlserver如何设置定时备份(SQL Server使用脚本实现自动备份的思路详解)
- dedecms缩略图插件(织梦DEDECMS有缩略图显示,没有显示随机指定图片的实现方法)
- php数组练习题答案(PHP 数组黑名单/白名单实例代码详解)
- python html文字分段(Python对HTML转义字符进行反转义的实现方法)
- laravel 开发自定义组件(laravel框架模板之公共模板、继承、包含实现方法分析)
- sql语句delete的用法(SQL删除语句DROP、TRUNCATE、 DELETE 的区别)
- mysql索引为什么是b+树(mysql 使用B+树索引有哪些优势)
- MySql开启远程连接
- 深入理解mysql日志(mysql 重要日志文件汇总)
- URL如何编码与解码
排行榜
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9