简体   繁体   中英

How to connect windows and android device over internet programmatically on Non-Local network

I want to connect android with windows so that i can send my custom data. so far i have only seen localhost examples. but i want to connect my android which is on Sim-internet with windows connected through Ethernet.

this is android's code so far(client)

socket = Socket(address, port)
outputStream = socket.getOutputStream()
outputStream.write(data)

and this is C# windows(server)

IPHostEntry ipHostInfo = await Dns.GetHostEntryAsync("localhost");//localServer
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint ipEndPoint = new(ipAddress, 10090);
Console.WriteLine("initiating " + ipEndPoint.Port + ", " + ipAddress.ToString());
using Socket listener = new(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


listener.Bind(ipEndPoint);
listener.Listen(100);

var handler = await listener.AcceptAsync();

while (true)
{
    // Receive message.
    var buffer = new byte[1_024];
    var received = await handler.ReceiveAsync(buffer, SocketFlags.None);
    var response = Encoding.UTF8.GetString(buffer, 0, received);

    var eom = "<|EOM|>";
    if (response.IndexOf(eom) > -1 /* is end of message */)
    {
        Console.WriteLine(
            $"Socket server received message: \"{response.Replace(eom, "")}\"");

        break;
    }
}

as you can see it is localhost which can only be accessed by localNetworked devices but i want to connect it over internet from different networked devices

How can i implement that.?

Your socket should bind to all addresses, not the local ( new IPEndPoint(IPAddress.Any, ...) ).

Your server is most likely behind a firewall/NAT so you need to setup port forwarding so your server can be accessed from the internet.

If the servers public IP address is static then you can use that. Otherwise you have to purchase a domain and configure a DNS server or use a free dynamic DNS service like No-IP or FreeDNS...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM