A receiving and sending TCP client with Go

I am trying to implement my own P2P network without using any library. I want to build a TCP Client which sends and receives messages from other nodes. So all nodes should be able to send and receive messages over tcp/ip.

My current Problem is that the when I start both clients: One Node is able to receive and send messages, but the other node just sends messages and cannot receive messages.

I think I need to implement a channel somehow, but I am really new into Go and don't know how to implement it. Any suggestions?

Code below:


package main

 func main() {

  address := "" // IP of the other node; hardcoded for now
  go startServer()


helpler.go :

package main

import (

func startClient(address string) {
 //connect to this socket
 connClient, _ := net.Dial("tcp", address)

for {

    //read in input from stdin
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Text to send: ")
    text, _ := reader.ReadString('\n')

    //send to socket
    fmt.Fprint(connClient, text+"\n")

    //listen for reply
    //message, _ := bufio.NewReader(connClient).ReadString('\n')
    //fmt.Print("Message from server: " + message)
func startServer() {

//listen on all interfaces
ln, _ := net.Listen("tcp", ":8081")

//accept connection on port
connServer, _ := ln.Accept()

//run loop forever
for {
    //will listen for message to process ending in newline(\n)
    message, _ := bufio.NewReader(connServer).ReadString('\n')

    //fmt.Print("Message Received:" + string(message))

    //sample process for string received
    //newmessage := strings.ToUpper(message)

    connServer.Write([]byte(message + "\n"))

1 answer

  • answered 2018-07-11 13:33 Francisco1844

    Newbie Go developer here, but there is one issue I can think off right off the bat. You can not have multiple processes listening in the same IP and port.

    You are likely having an issue with that, but because you are not checking for errors you are not catching it. If you had code to check for errors you likely would notice you are getting an error like this:

    2018/07/11 09:21:06 listen tcp bind: address already

    in use exit status 1

    Even if somehow that is not your issue, it is still a good idea to have the error checks.

    I recommend you add checks. For example

    Server side

    ln, err := net.Listen("tcp", "")
    if err != nil {

    Client side

      conn, err := net.Dial("tcp", "")
        if err != nil {
            fmt.Println("error:", err)

    I think I need to implement a channel somehow

    As stated, I am new to Go myself, but my understanding is that channels are an interprocess communication tool within the same program. Not related to multiple programs. If you search for go channels in your favorite search tool you can find more info, but don't believe it is what you are looking for.