0

looking for help with the following. I need to access live weather data made available on port 5556 of my device using python so I can then process it further.

The command nc 127.0.0.1 5556 at the command promt results in the following response:

20201107175011 th0 -0.5 93 -1.5 0
20201107175055 wind0 0 0.0 0.0 -0.5 0
20201107175045 rain0 0.0 153.8 0.0 0
20201107175041 thb0 21.6 32 4.2 899.0 1006.0 0 1
20201107175028 data10 0.00 0
20201107175028 data11 61.84 0
20201107175028 data12 1.00 0
20201107175028 data13 12.00 0
20201107175028 data15 106.00 0
20201107175028 data16 1.00 0
20201107175028 t9 50.5 0

Utilizing the following python script results in: OSError: [Errno 98] Address in use.

    !/usr/bin/env python

    import socket
    
    HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
    PORT = 5556        # Port to listen on (non-privileged ports are > 1023)
    
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen()
        conn, addr = s.accept()
        with conn:
            print('Connected by', addr)
            while True:
                data = conn.recv(1024)
                if not data:
                    break
                print(data)

What am I doing wrong? Is there a way for python to receive the same response that is received using netcat?

Thanks.

Baobab

3
  • 4
    You are using nc as a TCP client but based on your code you are trying to implement a TCP server using Python. If you want to implement a TCP client using Python you should not use bind, listen and accept but instead simply connect(HOST,PORT) Commented Nov 7, 2020 at 18:18
  • 1
    Did you actually write that script yourself? It looks like you simply copied it from somewhere, and didn't realize that it was the server, not a client. Commented Nov 7, 2020 at 18:20
  • Thank you for the pointers. It now works. Next will be to figure out how to convert the response to valid json format. Commented Nov 7, 2020 at 19:21

1 Answer 1

1

Using a client script rather than a server script works. Thanks.

#!/usr/bin/env python3

import socket

HOST = '127.0.0.1' 
PORT = 5556       

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    data = s.recv(1024)

print('Received', repr(data))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.