Python中的并行服务器

0 投票
1 回答
2530 浏览
提问于 2025-04-18 02:10

我想做一个可以同时处理多个客户端的并行服务器。这样客户端就可以同时向服务器发送消息。

我之前做的串行服务器运行得很好。我可以连接、写入、关闭连接,然后再重新连接,没问题。现在我想实现线程。也就是说:每当有一个新客户端连接时,就需要创建一个新的线程来处理与这个客户端的TCP连接。

这是我串行服务器的代码:

    #!/usr/bin/python           # This is server.py file

import socket               # Import socket module
import time

while True:
   s = socket.socket()         # Create a socket object
   host = socket.gethostname() # Get local machine name
   port = 12345                # Reserve a port for your service.
   s.bind((host, port))        # Bind to the port

   s.listen(5)                 # Now wait for client connection.

   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Please wait...')
   time.sleep(2)
   c.send('Thank you for connecting with your admin. Please write now.')

   while True:
      msg = c.recv(1024)
      if not msg:
         s.close()
         break
      elif msg == "close1234567890":
         print ("Connection with %s was closed by the client." % (addr[0]))
      else:
         print "%s: %s" % (addr[0], msg)

这是我尝试做的并行服务器:

import socket              
import time
import thread


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
s.bind((host, 50999))       
s.listen(5)                

def session(conn, addr):
   while True:
      print 'Got connection from', addr
      conn.send('Please wait...')
      time.sleep(2)
      conn.send('Thank you for connecting with your admin. Please write now.')

      while True:
         msg = conn.recv(1024)
         if not msg:
            s.close()
            break
         elif msg == "close1234567890":
            print ("Connection with %s was closed by the client." % (addr[0]))
         else:
            print "%s: %s" % (addr[0], msg)

while True:
    conn, addr = s.accept()
    try:
       thread.start_new_thread(session(conn, addr))
    finally:
       s.close()

出现了错误:我启动服务器时没有问题。然后我启动客户端,一切正常。我可以写消息,服务器也能打印出来。接着我启动第二个客户端,但在这个窗口里什么都没有发生。第二个客户端无法发送消息。

抱歉,我对线程完全是个新手;)

1 个回答

1

这是因为你用 s.close() 关闭了这个连接。下面是修改过的代码:

def session(conn, addr):
    while True:
        print 'Got connection from', addr
        conn.send('Please wait...')
        time.sleep(2)
        conn.send('Thank you for connecting with your admin. Please write now.')

        while True:
            msg = conn.recv(1024)
            if not msg:
                conn.close()
                break
            elif msg == "close1234567890":
                print ("Connection with %s was closed by the client." % (addr[0]))
            else:
                print "%s: %s" % (addr[0], msg)

while True:
    conn, addr = s.accept()
    thread.start_new_thread(session(conn, addr))

s.close()

我测试过了,效果很好。顺便说一下,我把你的代码:

host = socket.gethostname()
s.bind((host, 50999))

改成了 s.bind(('localhost', 50999))。我不太明白你为什么需要用机器名,原来的代码根本就不管用——把主机名绑定到一个连接上是没有意义的。

撰写回答