Android Socket Client接收数据

时间:2014-07-08 11:48:49

标签: java android sockets

我正在为android创建一个基本测试应用程序,它可以连接到套接字服务器并发送和接收数据。我已经能够从客户端发送数据到服务器工作,但似乎有问题让Android接收数据。服务器工作,因为我已经能够使用外部应用程序测试它。

这是我的代码

package com.socket_sending_and_receving_test;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Looper;
import android.os.Message;
import android.widget.Button;

import android.widget.TextView;
import android.os.Handler;
import android.app.Activity;
import android.os.Bundle;



import android.view.View;
import android.widget.EditText;

public class Sending_And_Receiving extends Activity {

    private Socket socket;

    String message = "";

    String mClientMsg;

    TextView text;

    final Handler myHandler = new Handler();

    int count = 0;

    public static String SERVERPORT;
    public static int SERVERPORT2;
    public static String SERVER_IP;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sending_and_receaving);
        text = (TextView) findViewById(R.id.textView);
        text.setText("0");


    }

    Handler myUpdateHandler = new Handler() {
        public void handleMessage(Message msg) {
            TextView tv = (TextView) findViewById(R.id.textView);
            tv.setText(mClientMsg);
            super.handleMessage(msg);
        }
    };

    class CommsThread implements Runnable {
        String st = null;
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                Message m = new Message();
                {
                    BufferedReader input = null;
                    try {
                        InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
                        BufferedReader reader = new BufferedReader(streamReader);
                        st = reader.readLine();
                        mClientMsg = st;
                        myUpdateHandler.sendMessage(m);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }



    public void connect(View view) {

        EditText ip = (EditText) findViewById(R.id.ip);
        EditText port = (EditText) findViewById(R.id.port);
        SERVER_IP = ip.getText().toString();
        SERVERPORT = port.getText().toString();
        new Thread(new ClientThread()).start();
        new Thread(new CommsThread()).start();



    }

    public void Disconnect(View view) {

        try {
            socket.shutdownInput();
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    public void onClick(View view) {
        try {
            EditText et = (EditText) findViewById(R.id.ko);
            String str = et.getText().toString();
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true
            );
            out.println(str);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                SERVERPORT2 = Integer.parseInt(SERVERPORT);

                socket = new Socket(serverAddr, SERVERPORT2);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }
}

连接完成后,应用程序崩溃。我不认为这是由于UI更新,但我认为这是由于接收数据。

这里是logcat

07-08 21:59:57.915    7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libEGL_mali.so
07-08 21:59:57.920    7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_mali.so
07-08 21:59:57.925    7041-7041/com.socket_sending_and_receving_test D/libEGL﹕ loaded /system/lib/egl/libGLESv2_mali.so
07-08 21:59:57.930    7041-7041/com.socket_sending_and_receving_test D/﹕ Device driver API match
    Device driver API version: 10
    User space API version: 10
07-08 21:59:57.930    7041-7041/com.socket_sending_and_receving_test D/﹕ mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012
07-08 21:59:57.965    7041-7041/com.socket_sending_and_receving_test D/OpenGLRenderer﹕ Enabling debug mode 0
07-08 21:59:57.965    7041-7041/com.socket_sending_and_receving_test E/SensorManager﹕ thread start
07-08 21:59:57.970    7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ registerListener :: handle = 0  name= LSM330DLC 3-axis Accelerometer delay= 200000 Listener= android.view.OrientationEventListener$SensorEventListenerImpl@42b1cf38
07-08 21:59:58.080    7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 21:59:58.080    7041-7041/com.socket_sending_and_receving_test E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-08 22:00:03.235    7041-7193/com.socket_sending_and_receving_test W/dalvikvm﹕ threadid=13: thread exiting with uncaught exception (group=0x41e792a0)
07-08 22:00:03.240    7041-7193/com.socket_sending_and_receving_test E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-2791
    java.lang.NullPointerException
            at com.socket_sending_and_receving_test.Sending_And_Receiving$CommsThread.run(Sending_And_Receiving.java:74)
            at java.lang.Thread.run(Thread.java:856)
07-08 22:00:03.320    7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ unregisterListener::  Listener= android.view.OrientationEventListener$SensorEventListenerImpl@42b1cf38
07-08 22:00:03.320    7041-7041/com.socket_sending_and_receving_test D/Sensors﹕ Remain listener = Sending .. normal delay 200ms
07-08 22:00:03.320    7041-7041/com.socket_sending_and_receving_test I/Sensors﹕ sendDelay --- 200000000
07-08 22:00:03.320    7041-7041/com.socket_sending_and_receving_test D/SensorManager﹕ JNI - sendDelay
07-08 22:00:03.320    7041-7041/com.socket_sending_and_receving_test I/SensorManager﹕ Set normal delay = true
07-08 22:00:09.870    7041-7041/com.socket_sending_and_receving_test I/Choreographer﹕ Skipped 392 frames!  The application may be doing too much work on its main thread.
07-08 22:00:11.680    7041-7193/com.socket_sending_and_receving_test I/Process﹕ Sending signal. PID: 7041 SIG: 9

非常感谢有关此问题的任何帮助

干杯:)

2 个答案:

答案 0 :(得分:1)

您的套接字为NULL。这是因为竞争条件:

new Thread(new ClientThread()).start();
new Thread(new CommsThread()).start();

这两个线程都是在这里启动的,但是当CommsThread尝试使用它时,ClientThread将初始化套接字。但此时尚未初始化。

您可以在socket = ...之后立即调用CommsThread的run(),或者如果您确实需要第二个线程,请在那里启动它。

答案 1 :(得分:0)

在ClientThread完成连接之前,您的CommsThread正在运行。所以,' socket'仍然是空的,你得到一个NPE。

这些绝对没有理由成为两个不同的主题。合并它们,以便首先建立连接,然后开始I / O.使用两个线程来执行必须顺序的任务基本上是无用的。