Ascii on TCP socket

走远了吗. 提交于 2019-12-01 10:28:05

Here's an example of writing to and reading from an echoing server.

A simplified excerpt:

    Socket echoSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;

    try {
        echoSocket = new Socket("taranis", 7);
        out = new PrintWriter(echoSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(
                                    echoSocket.getInputStream()));
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host: taranis.");
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for "
                           + "the connection to: taranis.");
        System.exit(1);
    }

BufferedReader stdIn = new BufferedReader(
                               new InputStreamReader(System.in));
String userInput;

while ((userInput = stdIn.readLine()) != null) {
    out.println(userInput);
    System.out.println("echo: " + in.readLine());
}

Not sure, I think this should work:

try (DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream())) {
    outToClient.write(stringMessage.getBytes("US-ASCII"));
} catch (IOException e) {}
user1459519

Not stated in the original question is whether ASCII control codes have to handled.

While the accepted answer works for printable ASCII characters I've had problems (on Windows 7 Enterprise SP1) using it for strings containing ASCII control codes, especially strings containing any of the java newline "characters", e.g. VT, CR, LF, etc. A workaround is to send the string as bytes and convert it back to a string at the far end.

See my answer to this question for how to handle that situation.

Reading Lines and byte[] from input stream

and my closely related question and it's accepted answer:

Need TCPIP client that blocks until a specific character sequence is received

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!