Android应用程序上的Java Socket Exception(Null)。在我的智慧结束

时间:2014-11-08 17:46:02

标签: java android sockets client

首先,大家好,

情况: 我已经开始编写(部分)一个程序,该程序应该发送(在这个阶段)发送一个简单的消息" Hello World!"从Android(客户端)到C#服务器(在我的计算机上)。 两个设备都通过wifi连接。

简单测试: 我做了sendTCP();在我的计算机上使用Java,并使用c#服务器对其进行测试,它运行良好。所以我把它复制到我的android代码中。并补充说:

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

到清单。

问题: 一旦我在手机上运行它(也尝试在模拟器上同样的问题)。单击按钮后,将抛出异常,异常.getMessage()== null .... 所以我的TextView更改为: asfdasnull 奇怪的是它只是null,而不是nullpointerexception。

任何人都可以帮助我吗?还是暗示我朝着正确的方向前进?

public class MainActivity extends ActionBarActivity {

    Button myButton;
    TextView label;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        myButton = (Button) findViewById(R.id.button1);
        label = (TextView) findViewById(R.id.textView1);


        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {               
                wtf("dsgfdsg1");
                try{
                sendTCP();
                }catch(Exception ex){
                    wtf("asfdas"+ex.getMessage());
                    //System.out.println(ex.getMessage());
                }
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public void sendTCP() throws Exception{

        String s = "Hello World!";
        byte[] msg = new byte[1024];
        msg = s.getBytes();

        Socket so = new Socket("192.168.1.100", 5004);
        OutputStream outstream = so.getOutputStream();
        DataOutputStream datastream = new DataOutputStream(outstream);
        datastream.write(msg, 0, s.length());

        datastream.close();
        outstream.close();
        so.close();
    }

    public void wtf(String s){
        label.setText(s);
    }
}

2 个答案:

答案 0 :(得分:0)

你有NetworkOnMainThreadExeption。将sendTCP()调用放在AsyncTask或线程中。

答案 1 :(得分:0)

这是快速回答的问题。我完全忘记了我需要获取getStackTrace()而不是获取Message()。

所以基本上我不得不把sendTCP()放到一个线程中并像魅力一样工作!

谢谢大家。

相关问题