40

そのため、オンライン ゲーム用に複数のクライアントを処理するためにソケットを必要とする 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
4

7 に答える 7

47

あなたの質問に基づいて:

私の質問は、以下のコードを使用して、複数のクライアントを接続するにはどうすればよいでしょうか? リストを試してみましたが、その形式がわかりません。複数のクライアントが同時に接続されていて、特定のクライアントにメッセージを送信できる場合、これをどのように実現できますか?

あなたが与えたコードを使用して、これを行うことができます:

#!/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 が述べたように、スレッドの代わりにプロセスを使用できます。また、pythonthreadingモジュールまたは他の非同期ソケット フレームワークを確認することもできます。注: 必要に応じて実装するためのチェックが残されています。これは単なる基本的なフレームワークです。

于 2016-10-31T21:40:26.117 に答える
18

accept新しいクライアント接続を継続的に提供できます。ただし、それと他のソケット呼び出しは通常ブロックしていることに注意してください。したがって、この時点でいくつかのオプションがあります。

  • メインスレッドが新しいクライアントの受け入れに戻る間、クライアントを処理するために新しいスレッドを開きます
  • 上記と同様ですが、スレッドの代わりにプロセスを使用します
  • Twisted などの非同期ソケット フレームワーク、またはその他多数の非同期ソケット フレームワークを使用する
于 2012-05-30T06:04:31.443 に答える
8

これは、優れた出発点となる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()

このような端末から試してみてください

$ 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.

おそらく、A Forking または Threading Mixinも使用する必要があります。

于 2012-05-30T06:05:04.150 に答える
-1
#!/usr/bin/python
import sys
import os
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         
port = 50000

try:
    s.bind((socket.gethostname() , port))
except socket.error as msg:
    print(str(msg))
s.listen(10)
conn, addr = s.accept()  
print 'Got connection from'+addr[0]+':'+str(addr[1]))
while 1:
        msg = s.recv(1024)
        print +addr[0]+, ' >> ', msg
        msg = raw_input('SERVER >>'),host
        s.send(msg)
s.close()
于 2017-10-27T16:56:20.093 に答える