Chinaunix首页 | 论坛 | 博客
  • 博客访问: 398616
  • 博文数量: 77
  • 博客积分: 2031
  • 博客等级: 大尉
  • 技术积分: 855
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-15 19:54
文章分类

全部博文(77)

文章存档

2011年(1)

2009年(52)

2008年(24)

我的朋友

分类: Python/Ruby

2009-03-24 16:24:43

转自IBM网站上的一段代码,可以直接运行,好好学习下。


#!/usr/bin/python

import socket
import select

#debug = False
debug = True

class ChatServer:

  def __init__( self, port ):
    if debug: print 'start init ChatServer'
    self.port = port
    self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    self.srvsock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
    self.srvsock.bind( ("", port) )
    self.srvsock.listen( 5 )

    self.descriptors = [self.srvsock]
    print 'ChatServer started on port %s' % port

  def run( self ):
    
    while 1:
      # Await an event on a readable socket descriptor
      (sread, swrite, sexc) = select.select( self.descriptors, [], [] )
     
      # Iterate through the tagged read descriptors
      for sock in sread:
        # Received a connect to the server (listening) socket
        if sock == self.srvsock:
          self.accept_new_connection()
        else:
          # Received something on a client socket
          str = sock.recv(100)
          # Check to see if the peer socket closed
          if str == '':
            host,port = sock.getpeername()
            str = 'Client left %s:%s\r\n' % (host, port)
            self.broadcast_string( str, sock )
            sock.close
            self.descriptors.remove(sock)
          else:
            host,port = sock.getpeername()
            newstr = '[%s:%s] %s' % (host, port, str)
            self.broadcast_string( newstr, sock )

  def accept_new_connection( self ):
    if debug: print 'accept new connection...'
    newsock, (remhost, remport) = self.srvsock.accept()
    self.descriptors.append( newsock )
    newsock.send("You're connected to the Python chatserver\r\n")
    str = 'Client joined %s:%s\r\n' % (remhost, remport)
    self.broadcast_string( str, newsock )

  def broadcast_string( self, str, omit_sock ):
    for sock in self.descriptors:
      if sock != self.srvsock and sock != omit_sock:
        sock.send(str)
    print str

myServer = ChatServer( 2828 ).run()
 
阅读(3112) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~