Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous Socket

Tags:

python

sockets

How do I connect with multiple clients? Once connected with multiple clients how do I receive individual data from each? From what I know I need to use something called "Asyncore". How do I implement this?

Client Class

import socket
class Client():
    def __init__(self):
        self.host = 'localhost'
        self.port = 5000

        self.s = socket.socket()
        self.s.connect((self.host, self.port))
        self.s.send(str.encode(input("What is your name ")))

x = Client()

Host Class

import socket
class Host():
    def __init__(self):
        self.host = 'localhost'
        self.port = 5000

        self.s = socket.socket()
        self.s.bind((self.host, self.port))
        self.s.listen(5)
        self.c, self.addr = self.s.accept()
        print("User from " + str(self.addr) + " has connected")
        while True:
            data = self.c.recv(1024)
            if not data:
                break

            print(str(self.addr) +" name is " + data.decode("utf-8"))
            #c.send(str.encode(whatever))
        self.c.close()

x = Host()
like image 253
JGerulskis Avatar asked Nov 01 '22 07:11

JGerulskis


1 Answers

Are you looking for this one? asyncore

Here is the link where you can find all the info related to async socket handler

https://docs.python.org/2/library/asyncore.html

EDIT: dano comment is great too

Enjoy

like image 125
Oscar Bralo Avatar answered Nov 11 '22 14:11

Oscar Bralo