(webSocket) Can't connect to server with phone

Sorry if this is the wrong topic. I’m just stumped and don’t know where to find information.

I created a small chat application. And a console application for the server. Rented VDS on Windows. And everything works fine. Except that I can’t connect to the server when I create a build for Android. Although everything works in Unity.

I came to the conclusion that I need an SSL/TLS certificate for Android to allow the connection. But this is a pain in the ass. I don’t even have a domain. And no knowledge of this.

Maybe I’m wrong? Can someone help with advice? Maybe another waaay? Something(

I’ll leave some lines of code, just in case.
Client side:

        try
        {
           // await webSocket.ConnectAsync(new Uri("ws://localhost:8080"), CancellationToken.None);
            await webSocket.ConnectAsync(new Uri("ws://45.143.93.104:8080"), CancellationToken.None); // ("ws://45.143.93.104:8080") или ("ws://localhost:8080")
            Debug.Log("Подключение к серверу успешно");
            StartReceivingMessages();
        }
        catch (Exception ex)

And server side:

    static async Task Main(string[] args)
    {
        //httpListener.Prefixes.Add("http://localhost:8080/"); //("http://*:8080/") или //("http://localhost:8080/")
        httpListener.Prefixes.Add("http://*:8080/");
        httpListener.Start();
        Console.WriteLine("WebSocket Server started.");

        LoadUsers();
        InitializeDefaultRooms();

        while (true)
        {
            var context = await httpListener.GetContextAsync();
            if (context.Request.IsWebSocketRequest)
            {
                ProcessClient(context);
            }
            else
            {
                context.Response.StatusCode = 400;
                context.Response.Close();
            }
        }
    }

What is this IP? if its your pc, are you sure it is accessible through your router to be accessed by the internet?

Its ip from my vps. And i can connect to it from my pc, but not from phone with same wi-fi.

whats the error you get on making a connection?

i have only “unable to connect the remote server”. if i can get something more let me know.

For debugging this issue I would try to add a route to your server code, e.g., so that it handles a HTTP GET request to http://*:8080/test.html that always responds with code 200 and just sends some text.
This way you can open a browser on your phone and load http://45.143.93.104:8080/test.html. If this page doesn’t load on your phone it is likely due some firewall or network configuration issue.

An unsecure WebSocket connection should work as long as the page itself is also hosted via http. However, if the page is hosted with https:// it will only be possible to connect to a secured WebSocket connection(wss://).

Another issue could be cross site requests. If your build is hosted on another url or uses a different port than the WebSocket server it will be considered a cross site request. You will need to set the Access-Control-Allow-Origin header in your WebSocket server implementation. For example Access-Control-Allow-Origin: * would work for all incoming origins.
Try adding this to your server code:

context.Response.Headers["Control-Allow-Origin"] = "*";

Ok. After spending a whole day to do two things. Setting up a domain and connecting a certificate… Actually three. Because I had to rewrite my entire old websocket… To the kernel. I can honestly say that it’s not the certificate.

I don’t really know how to make C# send anything to the site. But I checked it another way. VPS always works with nginx. When I go to the site I get “502 Bad Gateway nginx/1.27.3”. And when I turn on my “server” I get a 400 response on my computer and a white screen on my phone. This is not entirely correct, but I think everything is fineee here. (Actually, Bad Gateway was enough… i think).

About http and https I mentioned that everything works fine on the computer. So there is no error in the code. I checked locally and then with VPS. (Actually now its the same. Rediricted).

[quote=“MarcelPursche, post:6, topic:1592951”]
Another issue could be cross site requests. If your build is hosted on another url or uses a different port than the WebSocket server it will be considered a cross site request
[/quote] Personally, I can’t understand it. But I made different builds. With connection via domain and direct via IP. The result is always the same…

Thanks anyway. Just letting you know in case anyone needs it. (There probably aren’t many people dumb as me.)

Personally, I can’t understand it. But I made different builds. With connection via domain and direct via IP. The result is always the same…

Let’s say you run the Unity build, i.e., the website on a local nginx server on http://45.143.93.104/ (default port 80) and your C# WebSocket server runs on http://45.143.93.104:8080/ the browser will consider those different origins(because the port is different). It may work on http://localhost because the security rules for localhost are more relaxed in most browsers.

So when the browser tries to connect to http://45.143.93.104:8080/ via WebSocket it can fail if your C# WebSocket server is missing the line context.Response.Headers["Control-Allow-Origin"] = "*"; in the request handler method. That means it isn’t allowing cross origin requests (CORS).

If you want to find out what is going wrong on the phone:
You can connect to your Android phone with Chrome Dev Tools if you enable remote debugging.
This is very simple you just need to enable Developer Options on your phone and connect the phone via USB to your compute. Then on the compute you open Chome on the page chrome://inspect#devices and select your phone.
You can then check the browser console and the Network connections to see what is going wrong when connecting to the WebSocket server. You may need to open the Developer Tools first and then load the page in order to track all network requests.

I’ve changed a lot since the post. But I still can’t connect from Android.

Let’s forget about nginx. I removed it. Because of all these problems with ports.
I’ll add some code for context. But I’ll also explain it in words.

            var host = Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureServices(services =>
                    {
                        services.AddCors(); // Add CORS
                    });

                    webBuilder.UseKestrel(options =>
                    {
                        options.ConfigureHttpsDefaults(httpsOptions =>
                        {
                            httpsOptions.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 |
                                                      System.Security.Authentication.SslProtocols.Tls13; // ChatGPT say that older versions can prevent connect from new androids
                        });

                        options.ListenAnyIP(443, listenOptions =>
                        {
                            listenOptions.UseHttps("C:/mySite.pfx", "812231");
                        });
                    });

                    webBuilder.Configure(app =>
                    {
                        app.UseCors(builder => builder
                            .AllowAnyOrigin() // Add CORS
                            .AllowAnyMethod() // Add CORS
                            .AllowAnyHeader()); // Add CORS

                        app.UseWebSockets();

                        app.Run(async context =>
                        {
                            if (context.WebSockets.IsWebSocketRequest)
                            {
                                var webSocket = await context.WebSockets.AcceptWebSocketAsync();
                                await HandleWebSocket(context, webSocket);
                            }
                            else
                            {
                                context.Response.StatusCode = 400;
                                await context.Response.WriteAsync("Bad Request: Not a WebSocket request");
                                Console.WriteLine("Not a webSocket request");
                            }
                        });
                    });
                })

I’m bad at netcode so I used gpt chat a lot. I moved everything to port 443. The user joins the domain with a certificate on 443. So my code sends him the certificate and establishes a connection on 443 (I think). I added CORS after changing ports didn’t work out. And it do nothing. (Did the gpt chat add CORS correctly?)

So here a simple client side code. i changed only ws to wss. Since it usually use 443, so remove port.

    public async void ConnectToServer()
    {
        webSocket = new ClientWebSocket();

        try
        {
            await webSocket.ConnectAsync(new Uri("wss://antisfera.ru/"), CancellationToken.None);
            //await webSocket.ConnectAsync(new Uri("ws://localhost:8080"), CancellationToken.None);
            Debug.Log("Подключение к серверу успешно");
            StartReceivingMessages();
        }
        catch (Exception ex)
        {
            Debug.LogError($"Ошибка подключения: {ex.Message}");
            Debug.LogError($"StackTrace: {ex.StackTrace}");
        }

    }

And again i can connect only from PC. And my friends too.

Chrome Dev Tools only show me

Failed to load /favicon.ico:1 resource: the server responded with a status of 400 (Bad Request)
Failed to load antisfera.ru/:1  resource:  the server responded with a status of 400 (Bad Request)

This makes sense to me. This is what I get when I go to the site from a computer.
This seems to be the problem, but then I don’t understand why the builds work on PC.

Maybe you can advise me another way to implement the connection? It seems easier to learn something different than to fix this (for me).

When you said it is working when runnning on your computer did you mean in the Editor when clicking on “Play” or as a Web build?

Your code looks like you are using the ClientWebSocket from System.Net.WebSockets in your player code. However, System.Net is not supported on the Web platform. You will need to connect to the WebSocket server using either the browser WebSocket API directly or some of the available third-party plugins compatible with the Web platform.

Yeah, im using using System.Net.WebSockets. And after your message i was like whaaaa…
I started adding sharp websocket, µWebSockets, NativeWebSocket, unity-websocket from mikerochip. They all have different methods and had to be rewritten… But nothing worked.

But none of that matters. I only needed to add this

"<uses-permission android:name="android.permission.INTERNET" />"

to the android manifest.

Thanks you a lot. Without you, I would have dropped all this and gone to port to netcode for gameobject.
(im so bad)