Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a TCP client in golang

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")))
    }

}
like image 378
user3324984 Avatar asked Apr 17 '14 18:04

user3324984


People also ask

Does Golang support TCP and UDP protocol?

The Go net package provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.

What is TCP in Golang?

TCP Connection in Go We can use the Dial function to create a connection to the server from a client. Meanwhile, the Listen function starts a connection server. The Accept method waits for an incoming request and returns a connection. We can handle multiple requests concurrently with Goroutines.

What is TCP connection pooling?

Keepling TCP connection alive means that the connection is kept in ESTABLISHED state, even though there is no immediate need to transmit any data via the connection. Web servers use connection pools to manage these open connections to clients. A practical example of keeping TCP connection open.


1 Answers

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.

like image 180
siritinga Avatar answered Oct 11 '22 17:10

siritinga