欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python socket实现多对多全双工通信的方法

程序员文章站 2023-11-10 13:23:10
服务器:#server.py #!/usr/bin/env python #-*-coding:utf-8-*- import sys import str...

服务器:#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实现多对多全双工通信的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。