Cannot get Websocket (Python) working with Elastic Beanstalk

0

Hi,

I am new to coding and also to AWS, so please do not be to hard on me if this is a dumb question. For training purposes I am trying to create an app (Kotlin) with the backend (Python) running on Elastic Beanstalk. Everything is working fine except the websocket data transfer.

Here is the shortened Backend-Code:

Import...
app = application = Flask(__name__)
ping_timeout = 120
ping_interval = 60
socketio = SocketIO(application, cors_allowed_origins="*", engineio_logger=True, allowEIO3=True, ping_timeout=ping_timeout, ping_interval=ping_interval)
logging.basicConfig(level=logging.DEBUG)

@application.route('/send_test', methods=['POST'])
def send_test():
    socketio.emit('test', {'response': 'TEST RECEIVED!!!!!'})
    return "Success", 200

And this is the shortened Frontend-Code:

class MainActivity : AppCompatActivity(), TextToSpeech.OnInitListener, NavigationView.OnNavigationItemSelectedListener {
    private lateinit var socket: Socket
    override fun onCreate(savedInstanceState: Bundle?) {
        connectWebSocket()

    private fun connectWebSocket() {
        Log.d("MainActivity", "connectwebsocket called")
        val socketUrl = "ws://travel32.us-east-1.elasticbeanstalk.com"
        val job = Job()
        val coroutineScope = CoroutineScope(Dispatchers.IO + job)
        IO.setDefaultOkHttpWebSocketFactory(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build())
        IO.setDefaultOkHttpCallFactory(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build())
        coroutineScope.launch {
            socket = IO.socket(socketUrl, IO.Options().apply {
                reconnection = true
                reconnectionAttempts = Integer.MAX_VALUE
                reconnectionDelay = 1000 // 1 second
                reconnectionDelayMax = 5000 // 5 seconds
            })
            socket.connect()
            Log.d("MainActivity", "WebSocket connected")

            socket.on("test", testsocket)
            socket.on(Socket.EVENT_CONNECT, onConnect)
            socket.on(Socket.EVENT_DISCONNECT, onDisconnect)
            socket.on(Socket.EVENT_CONNECT_ERROR, onError)
        }
    }

    private val testsocket = Emitter.Listener { args ->
        runOnUiThread {
            val testresponse = args[0] as JSONObject
            Log.d("MainActivity", "Received TEST response: $testresponse")
        }
    }

In short, when pressing a button in the app, it sends a post to "domain/send_test" and just for test purposes it should send via websocket "Test Received!!!!" to the frontend. When I push the button, I can see that the send_test function in the backend gets called, but "Received TEST response: $testresponse" in MainActivity never gets logged. The web.stdout.log of my environment outputs this when send_test is called:

May 14 14:19:27 ip-172-31-13-189 web[2211]: jxIFnNaeB7crO36TAAAC: Sending packet MESSAGE data 2["test",{"response":"TEST RECEIVED!!!!!"}]
May 14 14:19:27 ip-172-31-13-189 web[2211]: INFO:engineio.server:jxIFnNaeB7crO36TAAAC: Sending packet MESSAGE data 2["test",{"response":"TEST RECEIVED!!!!!"}]
May 14 14:19:39 ip-172-31-13-189 web[2211]: jxIFnNaeB7crO36TAAAC: Sending packet MESSAGE data 2["test",{"response":"TEST RECEIVED!!!!!"}]
May 14 14:19:39 ip-172-31-13-189 web[2211]: INFO:engineio.server:jxIFnNaeB7crO36TAAAC: Sending packet MESSAGE data 2["test",{"response":"TEST RECEIVED!!!!!"}]
May 14 14:20:01 ip-172-31-13-189 web[2211]: jxIFnNaeB7crO36TAAAC: Sending packet PING data None
May 14 14:20:01 ip-172-31-13-189 web[2211]: INFO:engineio.server:jxIFnNaeB7crO36TAAAC: Sending packet PING data None
May 14 14:20:02 ip-172-31-13-189 web[2211]: luoag_u_sK4lq15kAAAE: Sending packet OPEN data {'sid': 'luoag_u_sK4lq15kAAAE', 'upgrades': ['websocket'], 'pingTimeout': 120000, 'pingInterval': 60000}
May 14 14:20:02 ip-172-31-13-189 web[2211]: INFO:engineio.server:luoag_u_sK4lq15kAAAE: Sending packet OPEN data {'sid': 'luoag_u_sK4lq15kAAAE', 'upgrades': ['websocket'], 'pingTimeout': 120000, 'pingInterval': 60000}
May 14 14:20:02 ip-172-31-13-189 web[2211]: luoag_u_sK4lq15kAAAE: Received packet MESSAGE data 0
May 14 14:20:02 ip-172-31-13-189 web[2211]: INFO:engineio.server:luoag_u_sK4lq15kAAAE: Received packet MESSAGE data 0
May 14 14:20:02 ip-172-31-13-189 web[2211]: luoag_u_sK4lq15kAAAE: Sending packet MESSAGE data 0{"sid":"1FGFeiKmah61v5UEAAAF"}
May 14 14:20:02 ip-172-31-13-189 web[2211]: INFO:engineio.server:luoag_u_sK4lq15kAAAE: Sending packet MESSAGE data 0{"sid":"1FGFeiKmah61v5UEAAAF"}
May 14 14:20:02 ip-172-31-13-189 web[2211]: luoag_u_sK4lq15kAAAE: Received request to upgrade to websocket
May 14 14:20:02 ip-172-31-13-189 web[2211]: INFO:engineio.server:luoag_u_sK4lq15kAAAE: Received request to upgrade to websocket
May 14 14:20:03 ip-172-31-13-189 web[2211]: luoag_u_sK4lq15kAAAE: Upgrade to websocket successful
May 14 14:20:03 ip-172-31-13-189 web[2211]: INFO:engineio.server:luoag_u_sK4lq15kAAAE: Upgrade to websocket successful

As you can see it tries to send the response but nothing is being received on the frontend. The original purpose is, that I have a function on the Backend which should return a value right away, but in another thread also calls an external API. When the answer of the external API is given, the function should additionally to the returned value also transfer the API response to the frontend.

I read a lot that the load balancer must be configured somehow to make it work with websockets, but all tutorials and forum posts are from long ago when the Elastic Beanstalk UI looked way different and I could not manage to get it working.

My app is running on "Single Instance (Free Tier)" Configuration and I did not configure a load balancer or anything else.

I am now trying to get it work for over a week and hope that anyone can help me out :) Thank you!

  • I'm not sure this helps; but with Beanstalk it configures a proxy automatically I think; either Apache or NGINX? I use Apache and I had to add some configuration to the apache config in order for it to support web sockets. If this seems helpful, I can post what I had to do to get it work, let me know.

asked 10 months ago115 views
No Answers

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions