在 Java 中通过套接字发送字符串而不是字节

2022-09-03 08:56:49

我如何使用getOutputStream方法发送strin。它只能发送他们提到的字节。到目前为止,我可以发送一个字节。但不是字符串值。

public void sendToPort() throws IOException {

    Socket socket = null;
    try {
        socket = new Socket("ip address", 4014);
        socket.getOutputStream().write(2); // have to insert the string
    } catch (UnknownHostException e) {
        System.err.print(e);
    } finally {
        socket.close();
    }

}

提前致谢


答案 1

如何使用打印器:

OutputStream outstream = socket .getOutputStream(); 
PrintWriter out = new PrintWriter(outstream);

String toSend = "String to send";

out.print(toSend );

编辑:找到了我自己的答案,并看到一个改进被讨论,但被遗漏了。以下是使用 OutputStreamWriter 编写字符串的更好方法:

    // Use encoding of your choice
    Writer out = new BufferedWriter(new OutputStreamWriter(
        new FileOutputStream(fileDir), "UTF8"));

    // append and flush in logical chunks
    out.append(toSend).append("\n");
    out.append("appending more before flushing").append("\n");
    out.flush(); 

答案 2

使用 OutputStreamWriter 类实现所需的目标

public void sendToPort() throws IOException {
    Socket socket = null;
    OutputStreamWriter osw;
    String str = "Hello World";
    try {
        socket = new Socket("ip address", 4014);
        osw =new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
        osw.write(str, 0, str.length());
    } catch (IOException e) {
        System.err.print(e);
    } catch (UnknownHostException e) {
        System.err.print(e);
    } finally {
        socket.close();
    }

}