⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ass3server.py

📁 python client server chatting program. Very basic.but it well presents the application of server and
💻 PY
字号:
import select,sys
import socket

class cp5377Server:

  def __init__( self, port ):
    self.port = port;
    self.serversock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    self.serversock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
    self.serversock.bind( ("", port) )
    self.serversock.listen( 5 )
    self.clientnames=["test"]
    self.socketlist = [self.serversock]
    print 'cp5377Server written by 11910986 Xiuliang Song started on port %s' % port


  def startServer( self ):
   
   while True:
    try:

     (sread, swrite, sexc) = select.select( self.socketlist, [], [] )

     for sock in sread:

      if sock == self.serversock:
        self.add_client()
      else:
        clientfile = sock.makefile( 'rw', 0 )
        str=clientfile.readline().strip()#get each line from the client

        if str=='quit.':#type quit. to quit
          host,port = sock.getpeername()
          str = 'Client left %s:%s\r\n' % (host, port)
          self.tell_everybody( str, sock )
          sock.send("\n You have guit the game!\r\n")
          sock.close()
          
          self.socketlist.remove(sock)
        else:
            if str!='':
              host,port = sock.getpeername()#get the nick name from the client
              nickname=self.clientnames[self.socketlist.index(sock)]
              word="said"
              newstr = '[%s @ %s %s] %s\n\r' % (nickname , port,word, str)
              self.tell_everybody( newstr, sock )
    except KeyboardInterrupt:
     sys.exit(0)


  def tell_everybody( self, str, omit_sock ):

      for sock in self.socketlist:
        if sock != self.serversock and sock != omit_sock:
          sock.send(str)#broadcast the chat
    
      print str,
      
      
  def add_client( self ):

      clientsock, (remhost, remport) = self.serversock.accept()
      self.socketlist.append( clientsock )#add new sock to the list
      clientfile = clientsock.makefile( 'rw', 0 )
      clientfile.write( "Please enter a nick name followed by ENTER: " )
      msg_received = clientfile.readline().strip()
      while msg_received=="":
          clientfile.write( "Please enter a nick name followed by ENTER: " )
          msg_received = clientfile.readline().strip()
      self.clientnames.append(msg_received)# add to client name list
      clientsock.send("You're connected to the Python cp5377Server\r\nYou can enter 'quit.' to quit the game!\r\n")
      str = 'Client joined %s:%s\r\n' % (remhost, remport)
      self.tell_everybody( str, clientsock )

  
myServer = cp5377Server( 5377 ).startServer()#start the server

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -