【问题标题】:Ascii on TCP socketTCP 套接字上的 Ascii
【发布时间】:2011-01-23 12:42:54
【问题描述】:

谁能给我一个通过 TCP 发送 Ascii msg 的示例?(在网上找不到示例)

谢谢,

射线。

【问题讨论】:

标签: java network-programming javadoc


【解决方案1】:

Here's an example 写入和读取回显服务器。

一个简化的摘录:

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

【讨论】:

  • 他需要 ASCII,在这种情况下任何阅读器都是无用的,只要 socket 的输入/输出流就可以了(不需要用 BufferedXXX 包装它们)
  • 我不同意 bestsss 的两个论点。首先,使用阅读器更安全(如果有一天他从 ASCII 切换到 Unicode,那就没有问题了)。其次,使用缓冲读取器对于速度是必要的(没有缓冲,由于不断轮询套接字,您会浪费很多时间)。最后,两者的结合速度快、兼容 unicode 并提供方便的方法(如 readLine() 而不是处理字节数组)
【解决方案2】:

不确定,我认为这应该可行:

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

【讨论】:

    【解决方案3】:

    原问题中没有说明是否必须处理ASCII控制码。

    虽然接受的答案适用于 printable ASCII 字符,但我在将它用于包含 ASCII 控制代码的字符串时遇到了问题(在 Windows 7 Enterprise SP1 上),尤其是包含任何 java 换行符“字符的字符串” “,例如VT、CR、LF 等。一种解决方法是将字符串作为字节发送,然后在远端将其转换回字符串。

    请参阅我对这个问题的回答,了解如何处理这种情况。

    Reading Lines and byte[] from input stream

    和我密切相关的问题和它被接受的答案:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2023-03-21
      • 2014-05-27
      相关资源
      最近更新 更多