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.

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a ton for the quick reply. Flushing the printwriter solved the problem. Why is it really important? The source stackoverflow.com/questions/6387579/… from where I took reference does not do it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.