dongyue934001 2015-02-01 23:03
浏览 67
已采纳

EchoServer(Java)未将消息返回给客户端(golang)

I am trying to create a TCP client (golang) server (Java) application where the client writes, the server echos this text and returns the message back to the client, which subsequently echos the reply.

Server code (Java):

public static void main(String[] args) throws Exception {

    int port = 4444;
    ServerSocket serverSocket = new ServerSocket(port);
    System.err.println("Started server on port " + port);

    while (true) {
        Socket clientSocket = serverSocket.accept();
        System.err.println("Accepted connection from client");

        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        String s;
        while ((s = in.readLine()) != null) {
            out.println(s);
            System.out.println(s);

        }

        System.err.println("Closing connection with client");
        out.close();
        in.close();
        clientSocket.close();
    }
}

Client code (golang):

package main

import (
    "net"
    "os"
)

func main() {
    strEcho := "Hello"
    servAddr := "localhost:4444"
    tcpAddr, err := net.ResolveTCPAddr("tcp", servAddr)
    if err != nil {
        println("ResolveTCPAddr failed:", err.Error())
        os.Exit(1)
    }

    conn, err := net.DialTCP("tcp", nil, tcpAddr)
    if err != nil {
        println("Dial failed:", err.Error())
        os.Exit(1)
    }

    _, err = conn.Write([]byte(strEcho))
    if err != nil {
        println("Write to server failed:", err.Error())
        os.Exit(1)
    }

    println("write to server = ", strEcho)

    reply := make([]byte, 1024)
    _, err = conn.Read(reply)

    if err != nil {
        println("Write to server failed:", err.Error())
        os.Exit(1)
    }

    println("reply from server=", string(reply))

    conn.Close()
}

When I start the Java server and then run the Go application, the server says that the connection has been accepted (i.e. "Accepted connection from client") but never returns the echo back to the client. The client stalls on "write to server = Hello" i.e. the write to the server works fine, but the read back to the client does not. Any idea why this is happening?

  • 写回答

1条回答 默认 最新

  • dongqu9972 2015-02-01 23:13
    关注

    Try sending a newline character to match the readLine statement on the server-side

    strEcho := "Hello
    "
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭