dongyue934001
dongyue934001
2015-02-01 23:03

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 dongqu9972 6年前

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

    strEcho := "Hello
    "
    
    点赞 评论 复制链接分享