使用Java将android手机连接到服务器套接字

时间:2013-02-21 21:11:11

标签: java android sockets connect serversocket

我正在Eclipse中编写Java代码来创建一个Android浏览器,当按下浏览器的Go按钮时,它会通过套接字与服务器通信。我已经看过几个例子,但仍然不知道我的代码有什么问题。我有正确的IP地址,我在代码的服务器和客户端使用相同的端口号。这是客户端代码减去import语句:

public class MainActivity3 extends Activity {

    EditText URLText;

    Button GoButton;
    WebView Browser;
    int SERVERPORT = 33333;
    String servernum = "10.215.23.109";
    private boolean connected = true;

    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity3);

        URLText = (EditText) findViewById(R.id.URL);
        GoButton = (Button) findViewById(R.id.Go);
        Browser = (WebView) findViewById(R.id.WebEngine);
        Browser.loadUrl("http://www.google.co.in/");

        GoButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                Browser.setWebViewClient(new MyWebViewClient());

                Thread cThread = new Thread(new ClientThread());
                cThread.start();

                Browser.loadUrl("http://" + URLText.getText().toString());

            }
        });
    }

    public class ClientThread implements Runnable {
        @Override
        public void run() {

            try {

                Log.d("ClientActivity", "C: Connecting...");
                Socket socket = new Socket(servernum, SERVERPORT);
            } catch (UnknownHostException e) {
                System.err.println(e);
            } catch (IOException e) {
                System.err.println(e);
            }
        }

        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.activity_main_activity3, menu);
            return true;
        }
    }
}

这是服务器代码:

public static void main(String[] args) throws IOException {
    int port = 33334;
    ServerSocket serverSocket = new ServerSocket(port);
    System.out.println("Server socket created at port # "+ port );
    Socket socket = serverSocket.accept();
    System.out.println("Socket accepted");
    System.out.println("Output created");

    socket.close();
    serverSocket.close();  
}

这基本上是一个测试代码,以确保手机将连接到服务器。当我在我的Linux终端上运行它时,它只输出“在端口#33334创建的服务器套接字”并等待手机连接从未发生的端口,即使我反复按下浏览器,这让我相信我的代码的客户端出了问题。

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

这与this post非常相似。

您可以使用DefaultHttpClient直接与服务器通信,而不是创建WebView:

try{
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://10.215.23.109:33333");
    HttpResponse response = client.execute(request);
}catch(Exception e){
    // Handle the exception
    e.printStackTrace();
}