在golang中创建一个TCP客户端。

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

Creating a TCP client in golang

问题

你好,以下是你提供的内容的中文翻译:

嗨,我正在尝试学习使用Go语言进行套接字编程,我正在按照这个教程进行学习:

http://synflood.at/tmp/golang-slides/mrmcd2012.html#1

这是教程的最终结果,放在一个页面上。

https://github.com/akrennmair/telnet-chat/blob/master/03_chat/chat.go

我对如何编写该程序的客户端部分感到困惑,我创建了一个连接并拨号到与服务器运行在同一端口/ IP上,但是从那里我就不知道该怎么做了。我已经为新创建的连接准备了read()和write()函数,但不知道在哪里分隔读取或其他操作。考虑到文本输入在服务器端处理,我想我只需要进行某种形式的读取?

package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:6000")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	for {
		fmt.Println(bufio.NewReader(conn).ReadString([]byte("\n")))
	}

}

希望对你有帮助!

英文:

Hi i'm attempted to learn some socket programming in golang, I'm following along with this tutorial

http://synflood.at/tmp/golang-slides/mrmcd2012.html#1

Here is the final result of the tutorial on one page.
https://github.com/akrennmair/telnet-chat/blob/master/03_chat/chat.go

I'm confused on how to write the client side of this program, I create a connection and dial into the same port/ip as the server is running on but from there I don't know. I have read() and write() functions for the newly created connection but no idea where to delimit the read or anything. Considering the text input is handeled in the server I imagine I'd only need to do a read of some kind?

package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:6000")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	for {
		fmt.Println(bufio.NewReader(conn).ReadString([]byte("\n")))
	}

}

答案1

得分: 12

bufio.NewReader应该只在代码中使用一次,在你的情况下,就在for之前使用。例如connbuf := bufio.NewReader(conn)。然后你可以在connbuf上使用ReadString,它会返回字符串和可能的错误。例如:

connbuf := bufio.NewReader(conn)
for {
    str, err := connbuf.ReadString('\n')
    if err != nil {
        break
    }

    if len(str) > 0 {
        fmt.Println(str)
    }
}

我检查lenerr是因为ReadString可能会返回数据和错误(连接错误、连接重置等),所以你需要同时检查它们。

英文:

bufio.NewReadershould be used only once, in your case, just before the for. For example connbuf := bufio.NewReader(conn). Then you can use ReadString on connbuf, that returns the string and maybe an error. For example:

connbuf := bufio.NewReader(conn)
for{
    str, err := connbuf.ReadString('\n')
    if err != nil {
        break
    }

    if len(str) > 0 {
        fmt.Println(str)
    }
}

I'm checking lenand err because ReadString may return data and an error (connection error, connection reset, etc.) so you need to check both.

答案2

得分: 1

以下是翻译好的内容:

这是一个简单的解决方案,如果你想读取所有接收到的数据。

connbuf := bufio.NewReader(c.m_socket)
// 读取第一个字节并设置底层缓冲区
b, _ := connbuf.ReadByte()
if connbuf.Buffered() > 0 {
var msgData []byte
msgData = append(msgData, b)
for connbuf.Buffered() > 0 {
// 逐字节读取,直到缓冲数据为空
b, err := connbuf.ReadByte()
if err == nil {
msgData = append(msgData, b)
} else {
log.Println("-------> 无法读取的字符...", b)
}
}
// msgData 现在包含了缓冲的数据...
}

英文:

Here is a simple solution if you want to read all received data.

    connbuf := bufio.NewReader(c.m_socket)
    // Read the first byte and set the underlying buffer
    b, _ := connbuf.ReadByte() 
    if connbuf.Buffered() > 0 {
    	var msgData []byte
    	msgData = append(msgData, b)
    	for connbuf.Buffered() > 0 {
    		// read byte by byte until the buffered data is not empty
    		b, err := connbuf.ReadByte()
    		if err == nil {
    			msgData = append(msgData, b)
    		} else {
    			log.Println("-------> unreadable caracter...", b)
    		}
    	}
    	// msgData now contain the buffered data...
    }

huangapple
  • 本文由 发表于 2014年4月18日 02:05:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/23140323.html
匿名

发表评论

匿名网友

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

确定