所以我正在开发一个需要套接字来处理多个客户端进行在线游戏的 iPhone 应用程序。我已经尝试过 Twisted,并且经过很多努力,我未能一次获得要发送的一堆信息,这就是我现在要尝试套接字的原因。
我的问题是,使用下面的代码,您如何能够连接多个客户端?我已经尝试过列表,但我无法弄清楚它的格式。在同时连接多个客户端并且我能够向特定客户端发送消息的情况下,如何实现这一点?
谢谢!
#!/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
最佳答案
根据您的问题:
My question is, using the code below, how would you be able to have multiple clients connected? I've tried lists, but I just can't figure out the format for that. How can this be accomplished where multiple clients are connected at once and I am able to send a message to a specific client?
使用您提供的代码,您可以这样做:
#!/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()
正如 Eli Bendersky 所说,您可以使用进程而不是线程,您还可以检查 python threading
模块或其他异步套接字框架。注意:检查留给您实现您想要的方式,这只是一个基本框架。
关于sockets - Python 套接字多个客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10810249/