Golang中的TCP/IP套接字通道不起作用。

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

Channels in Golang with TCP/IP socket not working

问题

我刚刚开始为我用C编写的带有TCP/IP套接字的服务器编写一个Golang客户端,然后我发现我的通道不起作用。

有什么想法为什么会这样?

func reader(r io.Reader, channel chan<- []byte) {
	buf := make([]byte, 2048)
	for {
		n, err := r.Read(buf[:])
		if err != nil {
			return
		}
		channel <- buf[0:n]
	}
}

func client(e *gowd.Element) {
	f, err := os.Create("/tmp/dat2")
	if err != nil {
		log.Fatal()
	}
	read := make(chan []byte)
	c, err := net.Dial("tcp", "127.0.0.1:4242")
	if err != nil {
		log.Fatal(err)
	}
	go reader(c, read)
	for {
		buf := <-read
		n := strings.Index(string(buf), "\n")
		if n == -1 {
			continue
		}
		msg := string(buf[0:n])
		if msg == "WELCOME" {
			fmt.Fprint(c, "GRAPHIC\n")
		}
		f.WriteString(msg + "\n")
	}
}

使用netcat测试我的服务器会产生以下输出:
http://pasted.co/a37b2954

但我只有:http://pasted.co/f13d56b4

我对Golang中的通道还不熟悉,所以可能我错了(我可能是错的)。

英文:

I just started writting a Golang client for a server that I've made in C with TCP/IP sockets, then I figured out that my channel wasn't working.

Any ideas why ?

func reader(r io.Reader, channel chan&lt;- []byte) {
  buf := make([]byte, 2048)
  for {
 	n, err := r.Read(buf[:])
	if err != nil {
		return
	}
	channel &lt;- buf[0:n]
  }
}
func client(e *gowd.Element) {
 f, err := os.Create(&quot;/tmp/dat2&quot;)
 if err != nil {
	log.Fatal()
 }
 read := make(chan []byte)
 c, err := net.Dial(&quot;tcp&quot;, &quot;127.0.0.1:4242&quot;)
 if err != nil {
	log.Fatal(err)
 }
 go reader(c, read)
 for {
	buf := &lt;-read
	n := strings.Index(string(buf), &quot;\n&quot;)
	if n == -1 {
		continue
 }
 msg := string(buf[0:n])
 if msg == &quot;WELCOME&quot; {
	fmt.Fprint(c, &quot;GRAPHIC\n&quot;)
 }
 f.WriteString(msg + &quot;\n&quot;)
}

Testing my server with netcat results in the following output :
http://pasted.co/a37b2954

But i only have : http://pasted.co/f13d56b4

I'm new to chan in Golang so maybe I'm wrong (I probably am)

答案1

得分: 2

通道使用看起来没问题,但是从通道中检索值会覆盖之前读取的值,因为你在等待换行符。

此外,你可以使用bufio.Reader来读取到换行符为止的字符串。

你提供的代码片段是不完整的,所以无法执行。你可以尝试一下,然后告诉我结果:

func reader(r io.Reader, channel chan<- string) {
    bufReader := bufio.NewReader(conn)
    for {
        msg, err := bufReader.ReadString('\n')
        if err != nil { // 连接错误或连接重置错误等
           break
        }
        channel <- msg
    }
}

func client(e *gowd.Element) {
    f, err := os.Create("/tmp/dat2")
    if err != nil {
        log.Fatal()
    }
    read := make(chan string)
    c, err := net.Dial("tcp", "127.0.0.1:4242")
    if err != nil {
        log.Fatal(err)
    }
    go reader(c, read)
    for {
        msg := <-read
        if msg == "WELCOME" {
            fmt.Fprint(c, "GRAPHIC\n")
        }
        f.WriteString(msg + "\n")
    }
    //...
}

编辑:

以下是一个通用的TCP客户端读取数据的示例。我已经从上面的代码片段中删除了扫描器,并添加了缓冲读取器。

func main() {
    conn, err := net.Dial("tcp", "127.0.0.1:4242")
    if err != nil {
        log.Fatal(err)
    }

    reader := bufio.NewReader(conn)
    for {
        msg, err := reader.ReadString('\n')
        if err != nil {
            break
        }
        fmt.Println(msg)
    }
}
英文:

Channel usage looks alright, however retrieving value from channel would overwrite previously read value at buf := &lt;-read since your waiting for newline.

Also you can use bufio.Reader to read string upto newline.

Your code snippet is partial so its not feasible to execute, try and let me know:

func reader(r io.Reader, channel chan&lt;- string) {
    bufReader := bufio.NewReader(conn)
    for {
        msg, err := bufReader.ReadString(&#39;\n&#39;)
        if err != nil { // connection error or connection reset error, etc
           break
        }
        channel &lt;- msg
    }
}
    
func client(e *gowd.Element) {
	f, err := os.Create(&quot;/tmp/dat2&quot;)
	if err != nil {
		log.Fatal()
	}
	read := make(chan string)
	c, err := net.Dial(&quot;tcp&quot;, &quot;127.0.0.1:4242&quot;)
	if err != nil {
		log.Fatal(err)
	}
	go reader(c, read)
	for {
		msg := &lt;-read
		if msg == &quot;WELCOME&quot; {
			fmt.Fprint(c, &quot;GRAPHIC\n&quot;)
		}
		f.WriteString(msg + &quot;\n&quot;)
	}
	//...
}

EDIT:

Please find example of generic TCP client to read data. Also I have removed scanner from above code snippet and added buffer reader.

func main() {
	conn, err := net.Dial(&quot;tcp&quot;, &quot;127.0.0.1:4242&quot;)
	if err != nil {
		log.Fatal(err)
	}

	reader := bufio.NewReader(conn)
	for {
		msg, err := reader.ReadString(&#39;\n&#39;)
		if err != nil {
			break
		}
		fmt.Println(msg)
	}
}

huangapple
  • 本文由 发表于 2017年7月3日 09:34:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/44876666.html
匿名

发表评论

匿名网友

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

确定