简体   繁体   中英

TCP/IP communication using Android as Client and C# as server

I want to send a few gyroscope readings from my android device to a PC program (C#) . I decided to do it via socket programming. Android phone acts as client and the Program running on the computer acting as the server. Here is my android code which sends "hello" for now :

try
{
    socket = new Socket("192.168.1.3", 1071);
PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
pw.println("Hello");
    socket.close();
}
catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }

and now the c# server code looks like this:

        listener = new TcpListener(1071);
        listener.Start();
        Socket soc;
        while (true)
        {
             soc= listener.AcceptSocket();
            Console.WriteLine("Connection accepted from " + soc.RemoteEndPoint);

            byte[] b = new byte[10000];
            int k = soc.Receive(b);
            Console.WriteLine(k);
            char cc = ' ';
            string test = null;
            Console.WriteLine("Recieved...");

            for (int i = 0; i < k - 1; i++)
            {
                Console.Write(Convert.ToChar(b[i]));
                cc = Convert.ToChar(b[i]);
                test += cc.ToString();
            }
        }
        soc.Close();
    }

The problem is that the connection is established, but I am not able to recieve anything at the server. The value of k is zero everytime. But the connection is successfull.

Output:
Connection accepted from 192.168.1.6:36742
0
Recieved...
Connection accepted from 192.168.1.6:57013
0
Recieved...

and so on.

Can anybody tell me what might be the issue, I am pretty sure that the encoding issues such as UTF-8 are not present.

看起来在关闭PrintWriter之前错过了刷新它。

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