python socket server in Heroku

Viewed 2168

Im trying to deploy a server using the socket module to heroku. The server runs correctly when I look at the logs from heroku, the problem is that i have not been able to connect to it with the client and it seems that an ip address is constantly connecting to the server.

Procfile: web: python Server.py

The server I built has this structure.

import socket
import os
from _thread import start_new_thread

PORT = int(os.environ(['PORT']))
HOST =  '0.0.0.0'

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

try:
    s.bind((HOST, PORT))
except socket.error as e:
    pass

s.listen(2)

def threaded_client(conn):
    print(f'CONNECTED -> {conn}')
    while True:
        # some logic
        pass



if __name__== '__main__':
    while True:
        conn, addr = s.accept()
        start_new_thread(threaded_client, (conn,))

And the client.

import socket


PORT = 80
HOST = 'https://my-heroku-app.herokuapp.com'

client =  socket.socket(socket.AF_INET,socket.SOCK_STREAM)

client.connect((HOST,PORT))

I have a similar issue as the one mentioned in here

Any insight would be appreciated. Thanks

1 Answers

you can't use heroku to host a tcp server ,you need a service like linode https://www.linode.com/ ,or aws ,but you can use heroku to host a websocket server which you can use a python websocket client to connect to ,like so

from websocket import create_connection
ws = create_connection("ws://myapp.herokuapp.com")
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result = ws.recv()
print("Received '%s'" % result)
ws.close()
Related