Skip to content
This repository has been archived by the owner on Oct 30, 2022. It is now read-only.

Commit

Permalink
websockets start
Browse files Browse the repository at this point in the history
  • Loading branch information
roby2014 committed Mar 1, 2022
1 parent 533d860 commit 2f398eb
Show file tree
Hide file tree
Showing 10 changed files with 439 additions and 8 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# csl-backend
## Combat Surf League API
# Combat Surf League API

`go run .` <br>
`go build -o bin/hello` <br>
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ require (
)

require (
github.com/gorilla/securecookie v1.1.1 // indirect
github.com/jmoiron/sqlx v1.3.4 // indirect
github.com/gorilla/websocket v1.5.0
github.com/jmoiron/sqlx v1.3.4
)
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyC
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jmoiron/sqlx v1.3.4 h1:wv+0IJZfL5z0uZoUjlpKgHkgaFSYD+r9CfrXjEXsO7w=
github.com/jmoiron/sqlx v1.3.4/go.mod h1:2BljVx/86SuTyjE+aPYlHCTNvZrnJXghYGpNiXLBMCQ=
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
Expand Down
10 changes: 10 additions & 0 deletions server.go → main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ import (
"github.com/robyzzz/csl-backend/controller"
"github.com/robyzzz/csl-backend/middleware"
"github.com/robyzzz/csl-backend/model"
"github.com/robyzzz/csl-backend/websocket"
)

var router *mux.Router

// start server
func main() {
config.GetEnvVariables()
model.Connect()
Expand All @@ -34,4 +36,12 @@ func setupRouter() {

// player stats
router.HandleFunc("/api/playerstats/{steamid}", controller.GetPlayerStats).Methods("GET")

//
websocket.WS = websocket.NewWebsocketServer()
go websocket.WS.Run()

log.Println("oia")

router.HandleFunc("/ws", websocket.ServeWs)
}
6 changes: 3 additions & 3 deletions model/player.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package model

type CSLPlayerStats struct {
type PlayerStats struct {
ID uint64 `json:"id"`
Player_SteamID string `json:"player_steamid"`
Map_ID int `json:"map_id"`
Expand All @@ -24,8 +24,8 @@ type CSLPlayerStats struct {
Mvp int `json:"mvp"`
}

func GetPlayerStats(steamID string) (CSLPlayerStats, error) {
user := CSLPlayerStats{}
func GetPlayerStats(steamID string) (PlayerStats, error) {
user := PlayerStats{}
err := db.Get(&user, "SELECT * FROM player_stats WHERE player_steamid = $1;", steamID)
return user, err
}
140 changes: 140 additions & 0 deletions websocket/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package websocket

import (
"encoding/json"
"log"
"net/http"

"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: func(r *http.Request) bool { return true },
}

type Client struct {
conn *websocket.Conn
wsServer *WsServer
send chan []byte
SteamID string `json:"steamid"`
Name string `json:"name"`
rooms map[*Room]bool
}

func NewClient(conn *websocket.Conn, wsServer *WsServer, name string, steamID string) *Client {
client := &Client{
SteamID: steamID,
Name: name,
conn: conn,
wsServer: wsServer,
send: make(chan []byte, 256),
rooms: make(map[*Room]bool),
}
return client
}

func ServeWs(w http.ResponseWriter, r *http.Request) {
// get params
name := r.URL.Query().Get("name")
steamid := r.URL.Query().Get("steamid")

if len(name) == 0 || len(steamid) == 0 {
log.Println("no name or no steamid")
return
}

// receive websocket connection
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("smt went wrong")
return
}

client := NewClient(conn, WS, name, steamid)

// handle I/O for client
go client.readPump()
go client.writePump()

WS.register <- client
}

func (client *Client) readPump() {
defer client.disconnect()

//client.conn.SetReadLimit(maxMessageSize)
//client.conn.SetReadDeadline(time.Now().Add(pongWait))
//client.conn.SetPongHandler(func(string) error { client.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })

// Start endless read loop, waiting for messages from client
for {
_, jsonMessage, err := client.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("unexpected close error: %v", err)
}
break
}

client.handleNewMessage(jsonMessage)
}
}

func (client *Client) writePump() {
defer client.conn.Close()
for {
select {
case message, ok := <-client.send:
log.Println("write pump")
if !ok {
// The WsServer closed the channel.
client.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}

w, err := client.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(message)

// Attach queued chat messages to the current websocket message.
n := len(client.send)
for i := 0; i < n; i++ {
w.Write([]byte("\n"))
w.Write(<-client.send)
}

if err := w.Close(); err != nil {
return
}

}
}
}

func (client *Client) disconnect() {
client.wsServer.unregister <- client
for room := range client.rooms {
room.unregister <- client
}
close(client.send)
client.conn.Close()
}

func (client *Client) handleNewMessage(jsonMessage []byte) {
var message Message
if err := json.Unmarshal(jsonMessage, &message); err != nil {
log.Printf("Error on unmarshal JSON message %s", err)
return
}

log.Println("handle new message: ")
log.Println(message)

// send msg
// join room
// leave room
}
111 changes: 111 additions & 0 deletions websocket/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chat Example</title>
<script type="text/javascript">
window.onload = function () {
var conn;
var msg = document.getElementById("msg");
var log = document.getElementById("log");

function appendLog(item) {
var doScroll = log.scrollTop > log.scrollHeight - log.clientHeight - 1;
log.appendChild(item);
if (doScroll) {
log.scrollTop = log.scrollHeight - log.clientHeight;
}
}

document.getElementById("form").onsubmit = function () {
if (!conn) {
return false;
}
if (!msg.value) {
return false;
}

var ya = {
action: "a",
message: msg.value,
target: "idk",
sender: {
steamid: "roby",
name: "pah ya",
},
}
console.log(JSON.stringify(ya))
conn.send(JSON.stringify(ya) );
msg.value = "";
return false;
};

if (window["WebSocket"]) {
let names = ["roby", "someone", "yaw", "dd", "brooks", "evai", "sirputin"]
const n = names[Math.floor(Math.random() * names.length)];
conn = new WebSocket(`ws://localhost:8081/ws?name=${n}&steamid=123`);
conn.onclose = function (evt) {
var item = document.createElement("div");
item.innerHTML = "<b>Connection closed.</b>";
appendLog(item);
};
conn.onmessage = function (evt) {
var messages = evt.data.split('\n');
for (var i = 0; i < messages.length; i++) {
var item = document.createElement("div");
item.innerText = messages[i];
appendLog(item);
}
};
} else {
var item = document.createElement("div");
item.innerHTML = "<b>Your browser does not support WebSockets.</b>";
appendLog(item);
}
};
</script>
<style type="text/css">
html {
overflow: hidden;
}

body {
overflow: hidden;
padding: 0;
margin: 0;
width: 100%;
height: 100%;
background: gray;
}

#log {
background: white;
margin: 0;
padding: 0.5em 0.5em 0.5em 0.5em;
position: absolute;
top: 0.5em;
left: 0.5em;
right: 0.5em;
bottom: 3em;
overflow: auto;
}

#form {
padding: 0 0.5em 0 0.5em;
margin: 0;
position: absolute;
bottom: 1em;
left: 0px;
width: 100%;
overflow: hidden;
}

</style>
</head>
<body>
<div id="log"></div>
<form id="form">
<input type="submit" value="Send" />
<input type="text" id="msg" size="64" autofocus />
</form>
</body>
</html>
26 changes: 26 additions & 0 deletions websocket/message.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package websocket

import (
"encoding/json"
"log"
)

const SendMessageAction = "send-message"
const JoinRoomAction = "join-room"
const LeaveRoomAction = "leave-room"

type Message struct {
Action string `json:"action"`
Message string `json:"message"`
Target string `json:"target"`
Sender *Client `json:"sender"`
}

func (message *Message) encode() []byte {
json, err := json.Marshal(message)
if err != nil {
log.Println(err)
}

return json
}
Loading

0 comments on commit 2f398eb

Please sign in to comment.