Forums

How to start a TCP socket on pythonanywhere and receive data

Hi pythonanywhere-Team, I have seen a few related posts but they didn't help me: Link1 Link2 Link3 Is it possible to start a TCP socket on pythoanywhere, what minimum code example do you recommend? Can I take this one and adapt it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python3

import socket

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # 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
            conn.sendall(data + b' from server')

It shall receive data and echo it back.

When trying to execute this code example, I receive the following error:

Traceback (most recent call last): File "/home/mydir/API/tcp_server_test.py", line 9, in <module> s.bind((HOST, PORT)) PermissionError: [Errno 13] Permission denied

How can I fix this and how can I properly configure the TCP connection under Web?

So from what I understand I can not connect to the socket externally. Link But eventually from a task / job that runs on pythonanywhere.

Is that correct?

You cannot connect externally and it's possible (but unlikely) that you'll be able to connect from within PythonAnywhere.