2016-04-21 74 views
1

請告訴我我的服務器代碼有什麼問題。它不能同時爲兩個客戶端工作。它僅爲我首先運行的客戶端運行。我是python和套接字編程的新手。請在這裏幫助我。服務器不適用於多個客戶端

import socket 
import sys 
import thread 
import time 
# Create a TCP/IP socket 
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

# Bind the socket to the address given on the command line 
server_address = ('127.0.0.1', 10001) 
data = " ".join(sys.argv[1:]) 
sock.bind(server_address) 
print >>sys.stderr, 'starting up on %s port %s' % sock.getsockname() 
sock.listen(1) 
connection, client_address = sock.accept() 
def my(threadName , delay): 

    while True: 
     print >>sys.stderr, 'waiting for a connection' 

     try: 
      print >>sys.stderr, 'client connected:', client_address 
      while True: 
       data = connection.recv(16) 
       print >>sys.stderr, 'received "%s"' % data 
       a=['a' ,'e', 'i' , 'o' , 'u'] 
       for i in data: 
        if i in a: 
         data = data.replace(i, '') 

         data=data.upper() 
         print data 


       print'\nUpper case string:' 

       if data: 
        connection.sendall(data) 
       else: 
        break 
     finally: 
      connection.close() 


thread.start_new_thread(my , ("Thread-1" , 8,)) 
thread.start_new_thread(my , ("Thread-2" , 10,)) 

回答

0

的主要問題是調用

connection, client_address = sock.accept() 

只有一次,因此只接受一個連接,然後繼續運行2個使用相同全局連接的線程。

不是服務器應該接受在一個循環中新的連接和連接都接受推出新的處理器:

from itertools import count 
from threading import Thread 

if __name__ == '__main__': 
    # Create a TCP/IP socket 
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

    # Bind the socket to the address given on the command line 
    server_address = ('127.0.0.1', 10001) 
    data = " ".join(sys.argv[1:]) 
    sock.bind(server_address) 
    print >>sys.stderr, 'starting up on %s port %s' % sock.getsockname() 
    sock.listen(1) 

    for i in count(1): 
     print >>sys.stderr, 'waiting for a connection' 
     # Blocked here until a new connection is accepted 
     connection, client_address = sock.accept() 
     name = "Thread-%d" % i 
     t = Thread(target=my, 
        args=(name, 8, connection, client_address), 
        name=name) 
     t.start() 

我把與higher-level threading interface改變你的低級別的線程API使用的自由。

處理函數應該接收連接作爲參數而不是使用全局變量,因爲連接對於該處理程序是唯一的。

from contextlib import closing 

def my(threadName, delay, connection, client_address): 
    print >>sys.stderr, 'client connected:', client_address 
    with closing(connection): 
     while True: 
      data = connection.recv(16) 
      print >>sys.stderr, 'received %r' % data 
      a = {'a' ,'e', 'i' , 'o' , 'u'} 
      for i in data: 
       if i in a: 
        data = data.replace(i, '') 

      data = data.upper()  
      print 'Upper case string:', data 

      if data: 
       connection.sendall(data) 

      else: 
       break 
相關問題