Android OkHttp3 client not receiving messages from C# WebSocket server

38 Views Asked by At

I've made an echo websocket server in c# and I'm trying to connect it to a client on an android app with Okhttp3.

I manage to establish a connection between the client and the server and the server receives messages from the client ("Hello from the companion app" is printed in the console). However, the client doesn't receive the return message from the server while another C# client receives it. When I do an echo test on an online server, the client receives the echo.

For cleartext traffic authorization in the app manifest, I followed this answer and added android:usesCleartextTraffic="true"

Here is my server code

using System;

using WebSocketSharp;
using WebSocketSharp.Server;

namespace testWebSockets
{
    public class Echo : WebSocketBehavior
    {
        protected override void OnOpen()
        {
            Console.WriteLine("Connection opened");
            Send("Hello, World!");
        }
        protected override void OnMessage(MessageEventArgs e)
        {
            Console.WriteLine("Received: " + e.Data);
            Send(e.Data);
        }

        protected override void OnClose(CloseEventArgs e)
        {
            base.OnClose(e);
            Console.WriteLine("Connection closed");
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            WebSocketServer wssv = new WebSocketServer("ws://0.0.0.0:8080");
            wssv.AddWebSocketService<Echo>("/Echo");

            wssv.Start();
            Console.WriteLine("Server started on ws://0.0.0.0:8080/Echo");

            Console.ReadKey();
            wssv.Stop(
        }
    }
}

And here is the MainActivity of the app.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val client = OkHttpClient()

        setContent {
            ConnectButton{connect(client)}
            Greeting("Mathieu")
        }

    }
}

The connect function

fun connect(client: OkHttpClient){
    val request : Request = Request
        .Builder()
        .url("ws://172.20.10.6:8080/Echo") // wss://socketsbay.com/wss/v2/1/demo/
        .build()

    val listener = WebSocketListener()
    val ws : WebSocket = client.newWebSocket(request, listener)

}

And the WebsocketListener class

package com.example.crossjwcompanion

import android.util.Log
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.text.Normalizer

class WebSocketListener : WebSocketListener(){

    override fun onOpen(webSocket: WebSocket, response: Response) {
        super.onOpen(webSocket, response)
        webSocket.send("Hello from the companion app")
        Log.e("WebSocketListener", "Client connected" )
        Log.e("WebSocketListener", "Message send" )

    }

    override fun onMessage(webSocket: WebSocket, text: String) {
        output("Message received: $text")
    }

    override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
        webSocket.close(NORMAL_CLOSURE_STATUS, null)
        output("Closing: $code / $reason")
    }

    override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
        output("Error : "+ t.message)
    }

    private fun output(text: String) {
        Log.d("WebSocketListener", text)

    }

    companion object{
        private const val NORMAL_CLOSURE_STATUS = 100
    }

}

Am I missing something?

EDIT: Since I posted this, I've implemented wss. I've created a self-signed certificate, which I've added to the android app manifest. I still have the same problem, the handshake is done but the client doesn't receive the messages from the server.

When I trace the server logs, I get this:

Server started on wss://localhost:8080/Echo 14/03/2024 16:22:05|Debug|WebSocket.InternalAccept|A request from 172.20.10.8:52144: GET /Echo HTTP/1.1 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: hLZ/TLzZ8GPxlg0EhiSo4A== Sec-WebSocket-Version: 13 Sec-WebSocket-Extensions: permessage-deflate Host: 172.20.10.6:8080 Accept-Encoding: gzip User-Agent: okhttp/4.12.0 14/03/2024 16:22:05|Debug|WebSocket.acceptHandshake|A response to this request: HTTP/1.1 101 Switching Protocols Server: websocket-sharp/1.0 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: STtAcslcDxi375kUwNcT73Wn7yc= Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover; server_no_context_takeover

Are there any clues in there?

0

There are 0 best solutions below