处理多个TCP客户端

huangapple go评论145阅读模式
英文:

Handling multiple Clients over TCP

问题

好的,以下是翻译好的内容:

好的,我刚开始学习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/simpler-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?

答案1

得分: -1

好的,以下是翻译好的内容:

好的,问题解决了。
有一个人实际上已经用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) {

huangapple
  • 本文由 发表于 2011年5月28日 21:43:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/6161993.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定