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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试