Python Socket Listening

前端 未结 2 1710
后悔当初
后悔当初 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:18

    If your in Python 3 by now and still wondering about sockets, here's a basic way of using them:

    server.py

    import time
    import socket
    
    # creating a socket object
    s = socket.socket(socket.AF_INET,
                      socket.SOCK_STREAM)
    
    # get local Host machine name
    host = socket.gethostname() # or just use (host == '')
    port = 9999
    
    # bind to pot
    s.bind((host, port))
    
    # Que up to 5 requests
    s.listen(5)
    
    while True:
        # establish connection
        clientSocket, addr = s.accept()
        print("got a connection from %s" % str(addr))
        currentTime = time.ctime(time.time()) + "\r\n"
        clientSocket.send(currentTime.encode('ascii'))
        clientSocket.close()
    

    client.py

    import socket
    
    # creates socket object
    s = socket.socket(socket.AF_INET,
                      socket.SOCK_STREAM)
    
    host = socket.gethostname() # or just use (host = '')
    port = 9999
    
    s.connect((host, port))
    
    tm = s.recv(1024) # msg can only be 1024 bytes long
    
    s.close()
    print("the time we got from the server is %s" % tm.decode('ascii'))
    

    Run server.py first, then run client.py

    This is just receive and send the currentTime.

    What's new in Python 3.4 sockets?

    A major difference between python 2.7 sockets and python 3.4 sockets is the sending messages. you have to .encode() (usually using 'ascii' or blank as parameters/arguments) and then using .decode()

    For example use .encode() to send, and use .decode() to receive.

    Extra info: client/server socket tutorial

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题