Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Android中使用Socket向远程服务器写入字符串消息_Java_Android_Sockets - Fatal编程技术网

Java 在Android中使用Socket向远程服务器写入字符串消息

Java 在Android中使用Socket向远程服务器写入字符串消息,java,android,sockets,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; Sock

我正在尝试使用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;
}

如果有人知道我做错了什么,

结果是我在发布到该服务器时使用了
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;
}

8080这是HTTP端口,因此您需要发送HTTP请求