Подтвердить что ты не робот

Многочисленные клиенты Python Socket

Итак, я работаю над 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
4b9b3361

Ответ 1

На основании вашего вопроса:

Мой вопрос, используя приведенный ниже код, как вы могли бы подключить несколько клиентов? Я пробовал списки, но я просто не могу понять формат для этого. Как это сделать, если одновременно подключено несколько клиентов, и я могу отправить сообщение определенному клиенту?

Используя код, который вы дали, вы можете сделать это:

#!/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 (addr,) not (addr) because second parameter is a tuple
   #Edit: (c,addr)
   #that how you pass arguments to functions when creating new threads using thread module.
s.close()

Как упоминал Эли Бендерский, вы можете использовать процессы вместо потоков, вы также можете проверить модуль python threading или другую платформу асинхронных сокетов. Примечание: проверки оставлены для вас, чтобы реализовать, как вы хотите, и это просто базовая структура.

Ответ 2

accept может непрерывно предоставлять новые клиентские соединения. Однако обратите внимание, что он и другие вызовы сокетов обычно блокируются. Поэтому на данный момент у вас есть несколько вариантов:

  • Откройте новые потоки для обработки клиентов, в то время как основной поток возвращается к принятию новых клиентов
  • Как и выше, но с процессами, а не с потоками
  • Используйте асинхронные фреймворки сокетов, такие как Twisted, или множество других.

Ответ 3

Вот пример из документации 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.

Возможно, вам также понадобится использовать миксин Forking или Threading too

Ответ 4

Эта программа откроет 26 сокетов, где вы сможете подключить к ней много клиентов TCP.

#!usr/bin/python
from thread import *
import socket
import sys

def clientthread(conn):
    buffer=""
    while True:
        data = conn.recv(8192)
        buffer+=data
        print buffer
    #conn.sendall(reply)
    conn.close()

def main():
    try:
        host = '192.168.1.3'
        port = 6666
        tot_socket = 26
        list_sock = []
        for i in range(tot_socket):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            s.bind((host, port+i))
            s.listen(10)
            list_sock.append(s)
            print "[*] Server listening on %s %d" %(host, (port+i))

        while 1:
            for j in range(len(list_sock)):
                conn, addr = list_sock[j].accept()
                print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
                start_new_thread(clientthread ,(conn,))
        s.close()

    except KeyboardInterrupt as msg:
        sys.exit(0)


if __name__ == "__main__":
    main()

Ответ 5

#!/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()

Ответ 6

import socket               # Import socket module
from _thread import *

def on_new_client(clientsocket,address):
    while True:
        msg = clientsocket.recv(1024)
        #do some checks and if msg == someWeirdSignal: break:
        print(address, ' >> ', 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.

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