Skip to content

Instantly share code, notes, and snippets.

View percybolmer's full-sized avatar

ProgrammingPercy percybolmer

View GitHub Profile
<div class="center">
<h1>Amazing Chat Application</h1>
<h3 id="chat-header">Currently in chat: general</h3>
<h3 id="connection-header">Connected to Websocket: false</h3>
<!--
Here is a form that allows us to select what Chatroom to be in
-->
<form id="chatroom-selection">
<label for="chatroom">Chatroom:</label>
var (
/**
websocketUpgrader is used to upgrade incomming HTTP requests into a persitent websocket connection
*/
websocketUpgrader = websocket.Upgrader{
// Apply the Origin Checker
CheckOrigin: checkOrigin,
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
// readMessages will start the client to read messages and handle them
// appropriatly.
// This is suppose to be ran as a goroutine
func (c *Client) readMessages() {
defer func() {
// Graceful Close the Connection once this
// function is done
c.manager.removeClient(c)
}()
// Set Max Size of Messages in Bytes
// readMessages will start the client to read messages and handle them
// appropriatly.
// This is suppose to be ran as a goroutine
func (c *Client) readMessages() {
defer func() {
// Graceful Close the Connection once this
// function is done
c.manager.removeClient(c)
}()
// writeMessages is a process that listens for new messages to output to the Client
func (c *Client) writeMessages() {
// Create a ticker that triggers a ping at given interval
ticker := time.NewTicker(pingInterval)
defer func() {
ticker.Stop()
// Graceful close if this triggers a closing
c.manager.removeClient(c)
}()
var (
// pongWait is how long we will await a pong response from client
pongWait = 10 * time.Second
// pingInterval has to be less than pongWait, We cant multiply by 0.9 to get 90% of time
// Because that can make decimals, so instead *9 / 10 to get 90%
// The reason why it has to be less than PingRequency is becuase otherwise it will send a new Ping before getting response
pingInterval = (pongWait * 9) / 10
)
package main
import (
"encoding/json"
"log"
"github.com/gorilla/websocket"
)
// ClientList is a map used to help manage a map of clients
...
var (
ErrEventNotSupported = errors.New("this event type is not supported")
)
// Manager is used to hold references to all Clients Registered, and Broadcasting etc
type Manager struct {
clients ClientList
package main
import "encoding/json"
// Event is the Messages sent over the websocket
// Used to differ between different actions
type Event struct {
// Type is the message type sent
Type string `json:"type"`
// Payload is the data Based on the Type
package main
import "encoding/json"
// Event is the Messages sent over the websocket
// Used to differ between different actions
type Event struct {
// Type is the message type sent
Type string `json:"type"`
// Payload is the data Based on the Type