Python Socket多客户端

Ale*_*lec 25 python sockets

所以我正在开发一款iPhone应用程序,它需要一个套接字来处理多个客户端以进行在线游戏.我已经尝试过Twisted,并且付出了很多努力,我没有立即获得一堆信息,这就是为什么我现在要尝试socket.

我的问题是,使用下面的代码,您将如何连接多个客户端?我已经尝试了列表,但我无法弄清楚它的格式.如何在一次连接多个客户端并且能够向特定客户端发送消息的情况下实现这一目标?

谢谢!

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

import socket               # Import socket module
s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50000                # Reserve a port for your service.

print 'Server started!'
print 'Waiting for clients...'

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
while True:
   msg = c.recv(1024)
   print addr, ' >> ', msg
   msg = raw_input('SERVER >> ')
   c.send(msg);
   #c.close()                # Close the connection
Run Code Online (Sandbox Code Playgroud)

jcc*_*uks 24

根据您的问题:

我的问题是,使用下面的代码,您将如何连接多个客户端?我已经尝试了列表,但我无法弄清楚它的格式.如何在一次连接多个客户端并且能够向特定客户端发送消息的情况下实现这一目标?

使用您提供的代码,您可以执行以下操作:

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

import socket               # Import socket module
import thread

def on_new_client(clientsocket,addr):
    while True:
        msg = clientsocket.recv(1024)
        #do some checks and if msg == someWeirdSignal: break:
        print addr, ' >> ', msg
        msg = raw_input('SERVER >> ')
        #Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.
        clientsocket.send(msg)
    clientsocket.close()

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50000                # Reserve a port for your service.

print 'Server started!'
print 'Waiting for clients...'

s.bind((host, port))        # Bind to the port
s.listen(5)                 # Now wait for client connection.

print 'Got connection from', addr
while True:
   c, addr = s.accept()     # Establish connection with client.
   thread.start_new_thread(on_new_client,(c,addr))
   #Note it's (addr,) not (addr) because second parameter is a tuple
   #Edit: (c,addr)
   #that's how you pass arguments to functions when creating new threads using thread module.
s.close()
Run Code Online (Sandbox Code Playgroud)

正如Eli Bendersky所提到的,你可以使用进程而不是线程,你也可以检查python threading模块或其他异步套接字框架.注意:检查留给您实现您想要的方式,这只是一个基本框架.

  • 函数中 `while True:` 之后的 `clientsocket.close()` 和底部 `while True:` 之后的 `s.close()` 永远不会被调用,因为没有 `break`在 `while True:` 中,退出循环的唯一方法是抛出异常,该异常不会被捕获并会结束线程。上下文管理器是确保套接字关闭的更好方法。 (2认同)
  • 至少对于 Python 3 来说,“import thread”不应该读取“from threading import Thread”和“thread.start_new_thread()”,然后替换为“Thread(target=on_new_client, args=(c,addr))”吗? (2认同)

Eli*_*sky 14

accept可以不断提供新的客户端连接.但是,请注意它,以及其他套接字调用通常是阻塞的.因此,您现在有几个选择:

  • 打开新线程来处理客户端,而主线程又回到接受新客户端
  • 如上所述,但使用进程,而不是线程
  • 使用像Twisted这样的异步套接字框架,或者使用过多的套接字框架

  • 对于第 3 点,Python 现在(3.5 以后)内置了对“asyncio”的异步编程支持 (3认同)

Nic*_*ood 5

以下是SocketServer文档中的示例,它将成为一个很好的起点

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()
Run Code Online (Sandbox Code Playgroud)

从这样的终端尝试

$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
HELLOConnection closed by foreign host.
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Sausage
SAUSAGEConnection closed by foreign host.
Run Code Online (Sandbox Code Playgroud)

你可能需要使用的分岔或螺纹密新

  • 有没有办法保持多个连接使用它? (4认同)