Source

GoTalk / client.go

Full commit
package main

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

func Log(v ...interface{}) {
    fmt.Println(v...)
}


func ServerHandler(conn net.Conn) {
    buffer := make([]byte, 1024)
    for {
        bytesRead, error := conn.Read(buffer)
        if error != nil {
            Log("connection error: ", error)
        }
        message := string(buffer[0:bytesRead])
        fmt.Print(message)
    }
}

// Main: connects to a TCP server and ask to the client for inputs
func main() {
    
    // Open connection
    conn, err := net.Dial("tcp", "localhost:9988")
    if err != nil {
        fmt.Println("Error", err.Error())
        return // terminate program
    }

    // Wait for messages from the server
    tcpAddr, error := net.ResolveTCPAddr("tcp", "localhost:1024")
    netListen, error := net.Listen(tcpAddr.Network(), tcpAddr.String())
    connection, error := netListen.Accept()
    go ServerHandler(connection)

    inputReader := bufio.NewReader(os.Stdin)
    fmt.Println("Please give yourname. Type Q to quit.")
    clientName, _ := inputReader.ReadString('\n')
    trimmedInput := strings.Trim(clientName, "\n")

    for {
        _, err = conn.Write([]byte(trimmedInput))
        fmt.Print("you> ")
        input, _ := inputReader.ReadString('\n')
        trimmedInput = strings.Trim(input, "\n")

        if trimmedInput == "Q" {
            return
        }

        
    }
}