我正在尝试创建一个 TCP 客户端(golang)服务器(Java)应用程序,客户端在其中写入,服务器回显此文本并将消息返回给客户端,客户端随后回显回复。
服务器代码(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();
}
}
客户端代码(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()
}
当我启动 Java 服务器,然后运行 Go 应用程序时,服务器说连接已被接受(即“接受来自客户端的连接”)但从未将回声返回给客户端。客户端停在“写入服务器 = Hello”,即写入服务器工作正常,但读回客户端没有。知道为什么会这样吗?
扬帆大鱼
相关分类