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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题