title: Go WebSocket server: Use of closed network connection
body: <p>I'm working on a websocket server and for some reason it outputs:</p>
  <blockquote>
  <p>&quot;WSARecv tcp 127.0.0.1:8080: Use of closed network connection.&quot;</p>
  </blockquote>
  <p>I don't know why it says that because I haven't closed the connection at any point in time.</p>
  <p>Below are some source code files of the server. If needed, the full source code is <a href="http://github.com/Kekocity/kekocity-go" rel="nofollow noreferrer">here on GitHub</a>.</p>
  <h2 id="connection.go-73nd">connection.go</h2>
  <pre><code>package net
  
  import (
    &quot;log&quot;
  
    &quot;golang.org/x/net/websocket&quot;
  
    pnet &quot;kekocity/misc/packet&quot;
    &quot;kekocity/interfaces&quot;
  )
  
  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 := &amp;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(&quot;net.connection: the user interface can not be nil!&quot;)
      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, &amp;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 := &lt;-c.txChan
  
      if message == nil {
        log.Println(&quot;SenPoller&quot;, &quot;The message is nil, break the loop&quot;)
        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(&quot;net.connection:&quot;, &quot;Received new packet!&quot;)
  }
  
  func (c *Connection) Close() {
    // Close channels
    close(c.txChan)
    close(c.rxChan)
  
    // Close the socket
    c.socket.Close()
  
    c.user = nil
  }
  </code></pre>
  <h2 id="server.go-2vqi">server.go</h2>
  <pre><code>package net
  
  // &lt;imports&gt;
  import (
    &quot;log&quot;
    &quot;fmt&quot;
    &quot;net/http&quot;
  
    &quot;golang.org/x/net/websocket&quot;
  
    pnet &quot;kekocity/misc/packet&quot;
    cmap &quot;kekocity/misc/concurrentmap&quot;
    &quot;kekocity/data/helpers&quot;
    &quot;kekocity/net/message&quot;
  )
  
  var server *Server
  
  type Server struct {
    port int
  
    connectedUsers *cmap.ConcurrentMap
  }
  
  func init() {
      server = newServer()
  }
  
  func newServer() *Server {
      return &amp;Server{
      port: 8080,
      connectedUsers: cmap.New(),
    }
  }
  
  func Listen(_port int) {
    server.port = _port
  
    log.Printf(&quot;Listening for connections on port %d!&quot;, _port)
  
    http.Handle(&quot;/ws&quot;, websocket.Handler(clientConnection))
  
      err := http.ListenAndServe(fmt.Sprintf(&quot;:%d&quot;, _port), nil)
      if err != nil {
          panic(&quot;ListenAndServe: &quot; + 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() != &quot;EOF&quot; {
        log.Println(&quot;net.server&quot;, &quot;Client connection error:&quot;, err.Error())
      }
    }
  }
  
  func parseFirstMessage(_conn *websocket.Conn, _packet *pnet.Packet) {
    _message := _packet.ToString()
  
    // If the first packet length is &lt; 1 close the socket
    if len(_message) &lt; 1 {
      _conn.Close()
      return
    }
  
    // Create the connection
    connection := NewConnection(_conn)
  
    // Authentication wrapper
    authPacket := &amp;message.AuthMessage{}
    user, err := helpers.AuthHelper.AuthenticateUsingCredentials(_message)
  
    if err != nil {
      log.Fatal(&quot;Invalid credentials!&quot;)
      authPacket.Status = &quot;error&quot;
    } else {
      // Need to check if its already logged
  
      authPacket.Status = &quot;success&quot;
  
      connection.AssignToUser(user)
        connection.txChan &lt;- authPacket
  
      return
    }
  
    // Send bad auth message and close
    connection.txChan &lt;- authPacket
    connection.Close()
  }
  </code></pre>
  <p>Full source code: <a href="http://github.com/Kekocity/kekocity-go" rel="nofollow noreferrer">github</a></p>