通过 TCP 处理多个客户端

发布于 2024-11-10 22:43:53 字数 836 浏览 0 评论 0原文

好吧,我刚刚开始学习 golang,到目前为止我很喜欢它。但是我发现他们的文档对初学者来说并不好,这是我的问题。 我想编写一个小服务器程序来接受连接并向客户端写入一些内容。到目前为止这样做没有问题。

然而,一旦它获得真正的功能,我就需要能够处理多个客户端,我认为这对于 goroutine 来说也是一个很好的练习。

listener, error := net.Listen("tcp", remote)
con, error := listener.Accept()
go handleClient(&con);
func handleClient(con *net.Conn) {

我已经删除了大部分代码。问题是,无论我尝试什么,我都无法通过 con

con.RemoteAddr undefined (type *net.Conn has no field or method RemoteAddr)

(发现在此示例中: http:// raycompstuff.blogspot.com/2009/12/simler-chat-server-and-client-in.html)。 所以我尝试查看文档,但它只给了我 net 包的来源。 阅读源代码,认为应该是

undefined: TCPConn

如何将客户端的连接传递给 goroutine,以便我可以同时处理多个客户端?

Okay, I just started learning golang and I like it so far. However I don't find their documentation good for go starters, Here is my problem.
I wanted to write little server program that accepts connections and writes something to the client. No problem doing that so far.

However as soon as the thing get a real functionality, I need to be able to handle multiple clients, which I though would also be a good exercise for goroutines.

listener, error := net.Listen("tcp", remote)
con, error := listener.Accept()
go handleClient(&con);
func handleClient(con *net.Conn) {

I've cut most of the code out. The problem is, no matter what I try, I can't pass con.

con.RemoteAddr undefined (type *net.Conn has no field or method RemoteAddr)

(found that in this example: http://raycompstuff.blogspot.com/2009/12/simpler-chat-server-and-client-in.html).
So i tried looking at the documentation, but it just gave me the source of the net package.
Read trough the source, and figured it should be

undefined: TCPConn

How can I pass the connection of a client to a goroutine, so i can handle multiple clients at once?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

纸伞微斜 2024-11-17 22:43:53

好吧,想通了。
实际上有人已经写了我想用 go 写的东西。
https://github.com/dustin/gomemcached/blob/master/mc_conn_handler.go

go handleClient(con);
func handleClient(con net.Conn) {

Ok, figured it out.
There is some guy who actually already wrote what I wanted to write in go.
https://github.com/dustin/gomemcached/blob/master/mc_conn_handler.go

go handleClient(con);
func handleClient(con net.Conn) {
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文