Python Socket Listening

前端 未结 2 1754
后悔当初
后悔当初 2020-12-30 11:08

All of the below mentioned is on windows machines using python 2.7

Hello,

I am currently attempting to listen on a socket for data send by a

2条回答
  •  我在风中等你
    2020-12-30 11:30

    Playing around with this for a while finally got it working nice with a telnet session locally using python 2.7.

    What it does is it sets up a thread that runs when the client connects listening for client stuff.

    When the client sends a return ("\r\n" might have to change that if your interacting with a Linux system?) the message gets printed to the server, while this is happening if there is a raw input at the server side this will get sent to the client:

    import socket
    import threading
    host = ''
    port = 50000
    connectionSevered=0
    
    class client(threading.Thread):
        def __init__(self, conn):
            super(client, self).__init__()
            self.conn = conn
            self.data = ""
        def run(self):
            while True:
                self.data = self.data + self.conn.recv(1024)
                if self.data.endswith(u"\r\n"):
                    print self.data
                    self.data = ""
    
        def send_msg(self,msg):
            self.conn.send(msg)
    
        def close(self):
            self.conn.close()
    
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((host,port))
        s.listen(5)
    except socket.error:
        print 'Failed to create socket'
        sys.exit()
    
    print '[+] Listening for connections on port: {0}'.format(port)
    
    
    conn, address = s.accept()
    c = client(conn)
    c.start()
    print '[+] Client connected: {0}'.format(address[0])
    c.send_msg(u"\r\n")
    print "connectionSevered:{0}".format(connectionSevered) 
    while (connectionSevered==0):
        try:
            response = raw_input()  
            c.send_msg(response + u"\r\n")
        except:
            c.close()
    

    The above answer will not work for more than a single connection. I have updated it by adding another thread for taking connections. It it now possible to have more than a single user connect.

    import socket
    import threading
    import sys
    host = ''
    port = 50000
    
    class client(threading.Thread):
        def __init__(self, conn):
            super(client, self).__init__()
            self.conn = conn
            self.data = ""
    
        def run(self):
            while True:
                self.data = self.data + self.conn.recv(1024)
                if self.data.endswith(u"\r\n"):
                    print self.data
                    self.data = ""
    
        def send_msg(self,msg):
            self.conn.send(msg)
    
        def close(self):
            self.conn.close()
    
    class connectionThread(threading.Thread):
        def __init__(self, host, port):
            super(connectionThread, self).__init__()
            try:
                self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.s.bind((host,port))
                self.s.listen(5)
            except socket.error:
                print 'Failed to create socket'
                sys.exit()
            self.clients = []
    
        def run(self):
            while True:
                conn, address = self.s.accept()
                c = client(conn)
                c.start()
                c.send_msg(u"\r\n")
                self.clients.append(c)
                print '[+] Client connected: {0}'.format(address[0])
    
    
    
    def main():
        get_conns = connectionThread(host, port)
        get_conns.start()
        while True:
            try:
                response = raw_input() 
                for c in get_conns.clients:
                    c.send_msg(response + u"\r\n")
            except KeyboardInterrupt:
                sys.exit()
    
    if __name__ == '__main__':
        main()
    

    Clients are not able to see what other clients say, messages from the server will be sent to all clients. I will leave that as an exercise for the reader.

提交回复
热议问题