使用Android中的Socket将字符串消息写入远程服务器

时间:2014-08-16 15:18:12

标签: java android sockets

我正在尝试使用Android中的Socket向远程服务器写一条简单的消息,我提供了远程服务器,这是我的尝试,它停在out.write

@Override
protected String doInBackground(String... params) {
    String comment = params[0];
    Log.i(TAG_STRING, "Comment is " + comment);
    String response = null;
    Socket socket = null;
    try {
        socket = new Socket("www.regisscis.net", 8080);
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        DataInputStream in = new DataInputStream(socket.getInputStream());
        Log.i(TAG_STRING, "Calling Write");
        out.writeBytes(comment);
        out.flush();
        String resposeFromServer = in.readUTF();
        out.close();
        in.close();
        response = resposeFromServer;               
        socket.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}

有谁知道我做错了什么,

1 个答案:

答案 0 :(得分:1)

当我发布到此服务器时,我会使用out.println("message")而不是out.write("message")。所以我已经更新了我的方法

@Override
protected String doInBackground(String... params) {
    String comment = params[0];
    String response = null;
    Socket socket = null;
    try {
        socket = new Socket("www.regisscis.net", 8080);
        if (socket.isConnected()) {
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            Log.i(TAG_STRING, "Calling Write");
            out.println(comment);
            String resposeFromServer = in.readLine();
            out.close();
            in.close();
            response = resposeFromServer;               
            socket.close();
        } else {
            Log.i(TAG_STRING, "Socket is not connected");
        }

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}