Python Socket Listening

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

提交回复
热议问题