How to make client on Android listen to server on C#?

后端 未结 3 1559
醉酒成梦
醉酒成梦 2020-12-13 23:17

I have a client on Android and server on c#. The client sends messages to server and it\'s fine. But I need server to send on request list of folders and files in specified

相关标签:
3条回答
  • Thank you for you code example!

    Just for info:

    you need the following permission being set:

        <uses-permission android:name="android.permission.INTERNET" />
    
    0 讨论(0)
  • 2020-12-13 23:48

    To avoid NetworkOnMainThreadException you need to execute the communication code in a new thread.

    In the Android client:

     @Override
     public void onClick(View v) {
    
     new Thread(new Runnable() {
            public void run() {
                connectSocket("Hello");
                    }
            }).start();
    
     }
    
    0 讨论(0)
  • 2020-12-13 23:49

    Ok, I found the solution to your problem.

    In your c# server where you send the text:

    ASCIIEncoding asen = new ASCIIEncoding();
    s.Send(asen.GetBytes("The string was recieved by the server."));
    s.Close();
    

    Make sure to close the socket here once you send the data. thats why your app would hang. IT was waiting for more input from the server

    Also, change to this in Java where you receive

    String text = "";
    String finalText = "";
    while ((text = in.readLine()) != null) {
        finalText += text;
        }
    txt.setText(finalText);
    

    Notice how you're doing 2 readInputs in that loop. The while statement does one.. and setting the text does one.. so you're essentially trying to read 2 lines during one loop. Changing to what i posted above will fix that

    0 讨论(0)
提交回复
热议问题