2

I'm working on a websocket server and for some reason it outputs:

"WSARecv tcp 127.0.0.1:8080: Use of closed network connection."

I don't know why it says that because I haven't closed the connection at any point in time.

Below are some source code files of the server. If needed, the full source code is here on GitHub.

connection.go

package net

import (
  "log"

  "golang.org/x/net/websocket"

  pnet "kekocity/misc/packet"
  "kekocity/interfaces"
)

type Connection struct {
  socket *websocket.Conn

  txChan chan pnet.INetMessageWriter
    rxChan chan pnet.INetMessageReader

  user interfaces.IUser
}

func NewConnection(_socket *websocket.Conn) *Connection {
  // The pointer allow us to modify connection struct from outside
  connection := &Connection{
    socket: _socket,
    txChan: make(chan pnet.INetMessageWriter),
    rxChan: make(chan pnet.INetMessageReader),
  }

  go connection.ReceivePoller()
  go connection.SendPoller()

  return connection
}

func (c *Connection) AssignToUser(_user interfaces.IUser) {
  if _user == nil {
    panic("net.connection: the user interface can not be nil!")
    return
  }

  c.user = _user
  _user.SetNetworkChans(c.rxChan, c.txChan)
}

/*
 * ReceivePoller and SendPoller starts listening when the first packet is verified and the new connection is started
 */
func (c *Connection) ReceivePoller() {
  for {
    packet := pnet.NewPacket()

    var buffer []uint8
        err := websocket.Message.Receive(c.socket, &buffer)

        if err == nil {
            copy(packet.Buffer[0:len(buffer)], buffer[0:len(buffer)])

            c.parsePacket(packet)
        } else {
            println(err.Error())
            break
        }
  }
}

func (c *Connection) SendPoller() {
  for {
    // Read messages from transmit channel
    message := <-c.txChan

    if message == nil {
      log.Println("SenPoller", "The message is nil, break the loop")
      break
    }

    // Convert netmessage to packet
    packet := message.WritePacket()
    packet.SetHeader()

    // Create byte buffer
    buffer := packet.GetBuffer()
    data := buffer[0:packet.GetMsgSize()]

    // Send bytes off to the internetz
    websocket.Message.Send(c.socket, data)
  }
}

func (c *Connection) parsePacket(_packet pnet.IPacket) {
  log.Println("net.connection:", "Received new packet!")
}

func (c *Connection) Close() {
  // Close channels
  close(c.txChan)
  close(c.rxChan)

  // Close the socket
  c.socket.Close()

  c.user = nil
}

server.go

package net

// <imports>
import (
  "log"
  "fmt"
  "net/http"

  "golang.org/x/net/websocket"

  pnet "kekocity/misc/packet"
  cmap "kekocity/misc/concurrentmap"
  "kekocity/data/helpers"
  "kekocity/net/message"
)

var server *Server

type Server struct {
  port int

  connectedUsers *cmap.ConcurrentMap
}

func init() {
    server = newServer()
}

func newServer() *Server {
    return &Server{
    port: 8080,
    connectedUsers: cmap.New(),
  }
}

func Listen(_port int) {
  server.port = _port

  log.Printf("Listening for connections on port %d!", _port)

  http.Handle("/ws", websocket.Handler(clientConnection))

    err := http.ListenAndServe(fmt.Sprintf(":%d", _port), nil)
    if err != nil {
        panic("ListenAndServe: " + err.Error())
    }
}

func clientConnection(clientsock *websocket.Conn) {
  packet := pnet.NewPacket()
  buffer := make([]uint8, pnet.PACKET_MAXSIZE)

  recv, err := clientsock.Read(buffer)

  if err == nil {
    copy(packet.Buffer[0:recv], buffer[0:recv])

    parseFirstMessage(clientsock, packet)
  } else {
    if err.Error() != "EOF" {
      log.Println("net.server", "Client connection error:", err.Error())
    }
  }
}

func parseFirstMessage(_conn *websocket.Conn, _packet *pnet.Packet) {
  _message := _packet.ToString()

  // If the first packet length is < 1 close the socket
  if len(_message) < 1 {
    _conn.Close()
    return
  }

  // Create the connection
  connection := NewConnection(_conn)

  // Authentication wrapper
  authPacket := &message.AuthMessage{}
  user, err := helpers.AuthHelper.AuthenticateUsingCredentials(_message)

  if err != nil {
    log.Fatal("Invalid credentials!")
    authPacket.Status = "error"
  } else {
    // Need to check if its already logged

    authPacket.Status = "success"

    connection.AssignToUser(user)
      connection.txChan <- authPacket

    return
  }

  // Send bad auth message and close
  connection.txChan <- authPacket
  connection.Close()
}

Full source code: github

6
  • What version of Go are you running and on what platform? There are many reports of something like this in the Go issue tracking system (and likely several different causes). One issue here looks like it has been fixed post v1.02 and someone else that had the issue reported it fixed when they switched to v1.2. There could also be other causes including logic error in your own code.
    – jfriend00
    Apr 26, 2015 at 16:16
  • Thanks for answering, I run Go 1.4.2 on windows. I think it's a logic error because sometimes in the client side i receive the message sent by the server but immediately the connection closes. Before asking this, I searched that can be causing this but I couldn't find anything in my code that can be causing this error. Apr 26, 2015 at 16:27
  • It is definitely an error in my code but i don't know how to solve it correctly. If i put a for loop under the "connection.AssignToUser(user) connection.txChan <- authPacket" the server don't closes the connection but above i call the function NewConnection() and it does that already with "go connection.ReceivePoller() go connection.SendPoller()" Apr 26, 2015 at 16:48
  • 3
    The websocket server closes the connection when the handler function clientConnection returns. I skimmed the code and didn't see anything that prevents the handler function from returning before the pollers are done. You should use the x/net package with caution as it does not fully implement the websocket protocol. Consider using Gorilla. Apr 26, 2015 at 23:03
  • 1
    The Gorilla not close the connection on return from handler. Should be easier for you. Apr 27, 2015 at 21:10

1 Answer 1

0

The context in the request is canceled right after the handler finishes.

serverHandler{c.server}.ServeHTTP(w, w.req)
w.cancelCtx()

This is the reason why your context. In this diagram, you can find how the context is created in the server.Serve method.

HTTP context livetime

It is described in more detail in the blog post: HTTP context livetime.

In the websocket, the situation is very similar. The context is closed just after the handler finishes.

func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) {
    rwc, buf, err := w.(http.Hijacker).Hijack()
    if err != nil {
        panic("Hijack failed: " + err.Error())
    }
    // The server should abort the WebSocket connection if it finds
    // the client did not send a handshake that matches with protocol
    // specification.
    defer rwc.Close() // <- here! It's executed when the s.Handler(conn) exites
    conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake)
    if err != nil {
        return
    }
    if conn == nil {
        panic("unexpected nil conn")
    }
    s.Handler(conn)
}

To fix that, you can create a new context from context.Background(), add some timeouts if needed and use it instead.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.