2

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.

Harsh Agrawal
  • 172
  • 2
  • 13

1 Answers1

3

It looks like you missed flushing your PrintWriter before you close it.

spender
  • 117,338
  • 33
  • 229
  • 351
  • 1
    Thanks a ton for the quick reply. Flushing the printwriter solved the problem. Why is it really important? The source http://stackoverflow.com/questions/6387579/how-to-make-client-on-android-listen-to-server-on-c from where I took reference does not do it – Harsh Agrawal Nov 30 '12 at 16:54