Android客户端服务器应用程序出错

时间:2015-12-20 10:41:20

标签: java android

我正在尝试创建一个程序,从我的Android手机连接到我的电脑上的Java应用程序。我尝试使用在计算机上工作的相同java代码但由于某种原因我得到java.lang.IllegalStateException:无法执行android:onClick错误的方法。我想应用程序通过TCP网络连接,以便我可以通过手机将数据发送到我的电脑。

我的代码     包com.ludwig.clientserver;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

public class MainActivity extends AppCompatActivity{

    Socket socket;

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

    public void sentToServer(View view) throws IOException{
        Thread thread = new Thread(new ClientServer());

        thread.start();
    }

    public class ClientServer implements Runnable{

        @Override
        public void run() {
            try {
                InetAddress serverAddress = InetAddress.getByName("192.168.1.9");
                socket = new Socket(serverAddress, 6789);
                TextView textView = (TextView) findViewById(R.id.output);
                textView.setText("Connected");
            }catch (Exception e){
                TextView textView = (TextView) findViewById(R.id.output);
                textView.setText("Connection Failed!");
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

0 个答案:

没有答案