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

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

本文介绍了在Java中通过套接字发送字符串而不是字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can i send a strin using getOutputStream method. It can only send byte as they mentioned. So far I can send a byte. but not a string value.

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();
    }

}

提前致谢

推荐答案

如何使用PrintWriter:

How about using PrintWriter:

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

String toSend = "String to send";

out.print(toSend );

编辑:找到我自己的答案并看到了改进,但已离开出。以下是使用 OutputStreamWriter :

EDIT: Found my own answer and saw an improvement was discussed but left out. Here is a better way to write strings using 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();

这篇关于在Java中通过套接字发送字符串而不是字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!