连接到远程服务器时套接字连接始终为空

时间:2015-10-12 16:46:51

标签: android sockets server

美好的一天。我正在尝试使用socket连接到服务器。这是我的代码,我是如何做到的。

 private class SocketConnection extends AsyncTask<String, String, String> {
        PrintWriter out;
        BufferedReader in;
        @Override
        protected String doInBackground(String... params) {
            connect();
            try {
                 out = new PrintWriter(clientSocket.getOutputStream());
                 in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (IOException ex) {
                System.out.append("error").append("socketcoonection").println();
            }

            String msg = null;
            try {
                msg = in.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }

            while (run) {
                System.out.append(msg).append("socketcoonection").println();
                out.println();
                out.flush();
                        /*try {
                            msg = in.readLine();
                        } catch (IOException ex) {
                            Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
                        }*/
            }

        return null;
    }
}

这是connect()方法

 public void connect() {
        try {
            clientSocket = new Socket("vaenterprises.org/test.php", 8080);
        } catch (UnknownHostException ex) {

        } catch (IOException ex) {

        }
        if (clientSocket != null) {
            run = true;
        }
    }

这是test.php

的服务器端php代码

echo json_encode("socket working");
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

并且地址链接是vaenterprises.org/test/php所以我试图连接到它并读取输入或输出流或者echo。无论我做什么,我在System.out.append(msg).append("socketcoonection").println();和调试期间得到nullPointerException想通了它的套接字是空的......请告诉我我做错了什么?

0 个答案:

没有答案