dregvw1801 2017-03-14 13:29
浏览 56
已采纳

套接字编程:是否在golang客户端或Java服务器中添加了额外的' '?

I've written a Java TCP socket service and this service is used by a golang client.

Things get weird when the server socket response gets parsed on the golang side.

Specifically, this Java server code:

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(output));
bw.append('Y');        
bw.append('E');
bw.append('S');
bw.append('
');
bw.flush();

And this golang client code:

extendTimoutFor(client.conn)
    rspMsg, fault := bufio.NewReader(client.conn).ReadString('
')
    if fault != nil {
        return UNKNOWN, fmt.Errorf("Ers reading response: %v", fault)
    }

    retStr := strings.TrimRight(rspMsg, "
")

    if retStr == YES {
        return YES, nil
    }

    if retStr == NO {
        return NO, nil
    }

    if retStr == FAIL {
        return FAIL, nil
    }

    return UNKNOWN, fmt.Errorf("Ers parsing msg [%s]: %v", rspMsg, fault)

Produce this result in the client:

[UNDO|test|]: Ers parsing msg [YES
]: <nil>

My problem with the result is that the client doesn't recognize retStr as a valid response. Since rspMsg is what we expect (i.e. 'YES ') then if we're in the UNKNOWN block it means that something went wrong during this line: retStr := strings.TrimRight(rspMsg, " ")?

My specific questions are:

  1. Since there are nil errors shouldn't ' ' and (any characters following it) have been stripped leaving us with "YES"?
  2. Am I missing some quirk on the Java side? I've recreated the client using Java and the output is what I expect.
  • 写回答

1条回答 默认 最新

  • du7535 2017-03-15 17:37
    关注
    1. Since there are nil errors shouldn't ' ' and (any characters following it) have been stripped leaving us with "YES"? YES

    2. Am I missing some quirk on the Java side? I've recreated the client using Java and the output is what I expect. YES

    This was resolved with a few steps:

    • Using java.io.PrintWriter introduced some unexpected characters throughout the output.
    • strings.TrimRight(rspMsg, " ") masked the point above but it was confirmed after installing Golang and debugging the script (using strings.TrimSpace for the operation above is a more robust approach)
    • Switching to java.io.OutputStream.write() simplified the output sent to the client
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样