开发者

Android 2.2 readUTF() Socket Problem

开发者 https://www.devze.com 2023-02-18 07:38 出处:网络
I am trying to create a Java Client-Server Program, where the Server is runni开发者_JAVA百科ng on a Windows PC, and the Client is running on an Android 2.2 Phone.

I am trying to create a Java Client-Server Program, where the Server is runni开发者_JAVA百科ng on a Windows PC, and the Client is running on an Android 2.2 Phone.

The Connection is okay. Sending Data from the Phone to the PC works also fine. Just receiving Data on the Phone crashes the program.

I am using DataInputStream and DataOutputStream to read/write through the Socket.

    //Thread on the Phone
    public void run() {
    while (RUN) {

        if (socket != null && socket.isConnected()) {
            try {
                //Crash
                String text = dis.readUTF();
                myTextView.setText(text);

            } catch (IOException ex) {
                //ErrorHandling
            }

        }

    }
}

I want to receive a String from the server and then show it in a TextView. Any Ideas? I am already setting this permission:

<uses-permission android:name="android.permission.INTERNET" />

do i need any other permissions? Thanks.


you can't set text on your UI if you're not in the UI thread.

do this...

add:

Runnable showmessage = new Runnable() { public void run() { myTextView.setText(membervariabletext); } };

and from your thread, after the readUTF(), call "runOnUiThread(showmessage);"


I would ensure that your Data Input Stream is initiated correctly:

Socket s = new Socket(serverAddress, port); DataInputStream dis = new DataInputStream(s.getInputStream());

Otherwise, here's a link for example code where someone uses InputStreamReader() and OutputStreamWriter() to make a server and client for Android.

https://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

0

精彩评论

暂无评论...
验证码 换一张
取 消