Geo Paul
Geo Paul

Reputation: 1817

Connection getting closed inside goroutine

I am writing a simple go program that connects with a socket server. I am using a goroutine to continuously look for the incoming messages. But inside the goroutine connection gets closed. Can someone suggest me what is happening?

Below is my test client

package main

import (
    "fmt"
    "net"
    "os"
    "encoding/json"
    "bufio"
)

type test_user struct {
    ID string
    Conn net.Conn
    Messages chan interface{}
}

func CreateTestUser(id string) test_user {
    return test_user{id, nil, nil}
}

/* 
1. Try connecting
2. Wait for connected packet
3. Send first packet (Init packet)
*/
func (user *test_user) Connect() {
    conn, err := net.Dial(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
    if err != nil {
        fmt.Println("Could not connect", err.Error())
        os.Exit(1)
    }
    user.Conn = conn
    user.Messages = make(chan interface{})
    reader := bufio.NewReader(conn)
    message, _ := reader.ReadBytes(DELIMITER)
    user.SendMessage(InitPacket{TYPE_USER,user.ID})
    //message, _ = reader.ReadBytes(DELIMITER)
    //message, _ = reader.ReadBytes(DELIMITER)  // If I uncomment these lines it will wait for new messages
    //message, _ = reader.ReadBytes(DELIMITER)
    go func() {
        for {
            var readErr error
            message, readErr = reader.ReadBytes(DELIMITER) // this always returns error "Error on read read tcp 127.0.0.1:54694->127.0.0.1:3333: use of closed network connection"/

            if readErr == nil {
                var packet interface{}
                error := json.Unmarshal(message, &packet)
                if error != nil {
                    fmt.Println("Unable to parse message", string(message), error.Error())
                }
                user.Messages <- packet
            } else {
                fmt.Println("Error on read", readErr.Error())
            }       
        }
    }()
}

Can someone please help me with this. Also I am new to golang to please suggests improvements as well.

Upvotes: 0

Views: 359

Answers (1)

Eli Bendersky
Eli Bendersky

Reputation: 273456

It'd be helpful to see a bit more of your code outside Connect.

Connect launches a new goroutine, but it doesn't wait for it - it returns immediately. Could the connection be closed after Connect returns?

Generally when you launch a goroutine to handle a connection, your "main" goroutine would keep waiting for other things - new connections and/or some handshake with the per-connection goroutines. I suspect this is not what's happening here.

Upvotes: 1

Related Questions