I'm trying to send a simple string between Android device and a C# application

on android as client

Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                Socket socket = new Socket("192.168.1.136",80);
                DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
                DOS.writeUTF("HELLO_WORLD");
                socket.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    thread.start();

on the PC as a server using C#

        byte[] byteReadStream = null; 
        IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
        TcpListener tcpl = new TcpListener(ipe);
        while (true)
        {
            tcpl.Start();
            TcpClient tcpc = tcpl.AcceptTcpClient();
            byteReadStream = new byte[tcpc.Available];
            tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
            Console.WriteLine(Encoding.Default.GetString(byteReadStream) + "\n");
        }

I have tried using specific IP and port it did not work

Bluetooth did not work

I have tried several posted codes on this site, all did not work. So maybe there this something that I am missing.

Please advice me on how to fix the code or a better way to send a string between android and windows app in any instant way.

Answer
      • 2
    • The client expects the server to listen on port 80. But the server listens on a random port. Specify a concrete port in the IPEndPoint constructor. And then use the same port in the client
      • 2
    • @NineBerry I have never used C# sockets but should "tcpl.start" be called outside the while loop? I just keep looking at the code and it doesnt follow normal tcp socket flow.
      • 2
    • using port 80 was my last test. I did try several ports, opening them in the firewall and disabling the firewall. I also tried to set a Specific port "9000" but it did not work. I always get host unreachable from the client side. I also never used sockets before so I am not sure how the normal tcp socket flow work.
      • 2
    • I'm not sure but you are opening a socket on port 80 and the other problem is that your socket in C# is not listening on a specific port...

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions