英文:
How to create client server in Go language?
问题
我是新手,正在尝试使用Go语言准备客户端服务器,并尝试编写代码,但没有输出。没有报错,只是在监听。
请有人帮助我,我想使用Go创建一个身份验证系统,其中服务器使用用户名和密码对客户端进行身份验证。
服务器:
package main
import (
"fmt"
"net"
)
func main() {
service := "0.0.0.0:8080"
tcpAddr, err := net.ResolveTCPAddr("tcp", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
_, err = conn.Read([]byte("HEAD"))
if err != nil {
conn.Close()
}
if err != nil {
continue
}
}
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
}
客户端:
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: ", os.Args[0], "host")
os.Exit(1)
}
host := os.Args[1]
conn, err := net.Dial("tcp", host+":8080")
checkError(err)
_, err = conn.Write([]byte("HEAD"))
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('\n')
line = strings.TrimRight(line, " \t\r\n")
if err != nil {
conn.Close()
break
}
}
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
}
英文:
I am new to go,
I was trying to prepare client server in go language and tried to write code, but it's not giving any output. It's not giving any error but just listening.
Please someone help me, I want to create authentication system using go where server authenticate client using Username password..
server :
package main
import (
"fmt"
"net"
)
func main() {
service := "0.0.0.0:8080"
tcpAddr, err := net.ResolveTCPAddr("tcp", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
//fmt.Println("Server listerning")
_, err = conn.Read([]byte("HEAD"))
if err != nil {
conn.Close()
}
if err != nil {
continue
}
}
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
}
client :
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: ", os.Args[0], "host")
os.Exit(1)
}
host := os.Args[1]
conn, err := net.Dial("tcp", host+":8080")
checkError(err)
_, err = conn.Write([]byte("HEAD"))
reader := bufio.NewReader(os.Stdin)
for {
line, err := reader.ReadString('\n')
ftm.Println(err)
line = strings.TrimRight(line, " \t\r\n")
if err != nil {
conn.Close()
break
}
}
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
}
}
答案1
得分: 5
我不确定你是否需要解析地址才能进行监听。
你应该只需要这样做:
listener, err := net.Listen("tcp", ":8080")
而且你在服务器端似乎没有对接收到的字节做任何处理(你丢弃了Read
的结果),这就解释了为什么你认为没有接收到任何内容。
请注意,你的代码一次只能处理一个连接。你应该在一个新的goroutine中处理每个打开的连接。
这里有一个相关问题中的客户端-服务器通信的TCP示例。
英文:
I'm not sure you need to resolve your address in order to listen.
You should be able to do just this :
listener, err := net.Listen("tcp", ":8080")
And you don't seem to do anything with the received bytes server side (you discard the result of Read
), which explains why you think you receive nothing.
Note that your code can only handle one connection at a time. You should handle each opened connection in a new goroutine.
Here's an example of client-server communication over TCP in a related question.
答案2
得分: 2
我不确定你期望的输出是什么,因为在我看来,你只是在客户端读取输入,而没有打印任何内容。正如@dystroy指出的,服务器只是丢弃它接收到的内容,只检查通信中的错误。
此外,你的服务器似乎应该只是坐在那里监听,因为你将其放在一个循环中只做这个。如果你查看net包的文档,它提供了一个运行服务器和客户端的示例。这是我从中制作的一个示例,对我来说有效。
服务器:
ln, err := net.Listen("tcp", ":8080")
// 处理错误
for {
conn, err := ln.Accept()
// 处理错误
var cmd []byte
fmt.Fscan(conn, &cmd)
fmt.Println("Message:", string(cmd))
}
客户端:
conn, err := net.Dial("tcp", "127.0.0.1:8080")
// 处理错误
fmt.Fprintf(conn, "message\n")
编辑以添加:这个程序的预期结果是你运行服务器并等待。然后在不同的终端中运行客户端,它立即退出,但现在服务器已经打印了"Message: message"。如果你再次运行客户端,服务器将再次打印相同的消息。我在我的机器上测试了这段代码(只添加了处理错误的代码),它按照广告上的方式工作。
英文:
I'm not sure exactly what output your expecting, as it seems to me that you are not printing anything out, just reading input in the client. As @dystroy pointed out, the server then discards what it received, only checking for errors in the communication.
Also, it seems that your server should just sit there listening, as you have it in a loop doing just that. If you look in the docs for the net package, it gives an example of how to run a server and client. Here's a sample that I made from that, that worked for me.
Server:
ln, err := net.Listen("tcp", ":8080")
// handle error
for {
conn, err := ln.Accept()
// handle error
var cmd []byte
fmt.Fscan(conn, &cmd)
fmt.Println("Message:", string(cmd))
}
Client:
conn, err := net.Dial("tcp", "127.0.0.1:8080")
// handle error
fmt.Fprintf(conn, "message\n")
Edited to add: The expected result of this program is that you run the server and it sits waiting. You then run the client in a different terminal, which immediately exits, but now the server has printed "Message: message". If you run the client again, the server will print the same message again. I tested this code on my machine (just adding code to respond to errors) and it worked as advertised.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论