【问题标题】:Client only socket programming in androidandroid中仅客户端的套接字编程
【发布时间】:2015-05-16 17:59:16
【问题描述】:

我想打开一个 TCP 连接以将数据发送到一个 android 应用程序中的一个 IP 地址。我发现的每一篇套接字编程文章/线程都显示了客户端和服务器端代码(通常是聊天程序)。是否可以让客户端代码在 android 设备上运行并将任意数据发送到例如 google 的 IP 地址?现在我正在使用这个线程中的代码(最高投票的答案)Android Client socket , how to read data? 在一个扩展 AsynchTask 的类中,如下所示:

public class InternetTask extends AsyncTask<Void, Integer, Void> {
    public static final int BUFFER_SIZE = 2048;
    private Socket socket = null;
    private PrintWriter out = null;
    private BufferedReader in = null;
    private int port = 80;
    private String host = null;
    private static final String TAG="sure2015test";

    public InternetTask(String host,int port) {
        this.host=host;
        this.port=port;
    }

    @Override
    protected Void doInBackground(Void... args) {


        connectWithServer();
        Log.i(TAG, "Connected");
        sendDataWithString("hello");
        Log.i(TAG, "Sent data");
        String response=receiveDataFromServer();
        Log.i(TAG,response);
        disConnectWithServer();
        return null;
    }


    private void connectWithServer() {
        try {
            if (socket == null) {
                socket = new Socket(this.host, this.port);
                out = new PrintWriter(socket.getOutputStream());
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            }
        } catch (IOException e) {
            Log.i(TAG,"IO Exeception");
            e.printStackTrace();
        }
    }

    private void disConnectWithServer() {
        if (socket != null) {
            if (socket.isConnected()) {
                try {
                    in.close();
                    out.close();
                    socket.close();
                } catch (IOException e) {
                    Log.i(TAG,"IO exception disconnecting");
                    e.printStackTrace();
                }
            }
        }
    }

    public void sendDataWithString(String message) {
        if (message != null) {
            connectWithServer();
            out.write(message);
            out.flush();
        }
    }

    public String receiveDataFromServer() {
        try {
            String message = "";
            int charsRead = 0;
            char[] buffer = new char[BUFFER_SIZE];
            Log.i(TAG,"Message before: "+message);
            while ((charsRead = in.read(buffer)) != -1) {
                message += new String(buffer).substring(0, charsRead);
                Log.i(TAG,message);
            }
            Log.i(TAG,"Message after: "+message);
            disConnectWithServer(); // disconnect server
            return message;
        } catch (IOException e) {
            Log.i(TAG,"IO Error in receiving message");
            return "Error receiving response:  " + e.getMessage();
        }
    }
}

还有我在 MainActivity.java 中的 onCreate 方法

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    InternetTask task=new InternetTask("74.125.226.159",80);
    task.execute();
}

当我运行它时,我会在日志中得到这个:

05-16 00:01:04.368      622-637/? I/sure2015test﹕ Connected
05-16 00:01:04.369      622-637/? I/sure2015test﹕ Sent data
05-16 00:01:04.369      622-637/? I/sure2015test﹕ Message before:
05-16 00:03:04.405      622-637/com.example.connorstein.sockethelloworld I/sure2015test﹕ Message after:

因此,在使用 google 的 IP 在端口 80 上打开套接字时没有异常,发送或接收数据也没有异常。看起来我只是没有回应。这是预期的,因为我发送的数据(“你好”)没有意义吗?我认为至少我会得到一个回复​​说无效请求或类似的东西。我也尝试发送“GET / HTTP/1.0”,但也没有响应。

【问题讨论】:

    标签: java android sockets http tcp


    【解决方案1】:

    Google 响应空白,因为您没有向其发送正确的 HTTP 请求。模仿普通网络浏览器的请求,你会得到响应。 HTTP 是建立在 TCP 之上的协议。您需要遵循协议才能从服务器中获取任何有用的信息。

    获得响应的最小浏览器标头示例:

    GET / HTTP/1.1\r\nUser-Agent: curl/7.37.1\r\nHost: www.google.com\r\nAccept: */*\r\n\r\n
    

    考虑使用 SSH 服务器,而不是使用 Web 服务器。 SSH 服务器会发送类似...

    SSH-2.0-OpenSSH_5.3\r\n
    

    ...连接时。始终响应的服务器更容易对客户端代码进行故障排除。请注意,您可能会使系统管理员疯狂地不断连接到他们的 ssh 服务器。您可能需要设置自己的测试对象。

    【讨论】:

    • 我仍然收到您的 GET 请求的空白响应
    • 没关系,我对请求的剪切和粘贴无法正常工作。有用!我只需要\r\n\r\n。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 2012-03-29
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多