Skip to content

Commit

Permalink
First commit using websocket from example from go web page
Browse files Browse the repository at this point in the history
  • Loading branch information
kbca committed Feb 16, 2022
0 parents commit dadc4b9
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bin
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module kbca/sudoku

go 1.17

require github.com/gorilla/websocket v1.5.0 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
41 changes: 41 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import (
"fmt"
"net/http"

"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}

func main() {
http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity

for {
// Read message from browser
msgType, msg, err := conn.ReadMessage()
if err != nil {
return
}

// Print the message to the console
fmt.Printf("%s sent: %s\n", conn.RemoteAddr(), string(msg))

// Write message back to browser
if err = conn.WriteMessage(msgType, msg); err != nil {
return
}
}
})

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "websockets.html")
})

http.ListenAndServe(":8080", nil)
}
21 changes: 21 additions & 0 deletions websockets.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<input id="input" type="text" />
<button onclick="send()">Send</button>
<pre id="output"></pre>
<script>
var input = document.getElementById("input");
var output = document.getElementById("output");
var socket = new WebSocket("ws://localhost:8080/echo");

socket.onopen = function () {
output.innerHTML += "Status: Connected\n";
};

socket.onmessage = function (e) {
output.innerHTML += "Server: " + e.data + "\n";
};

function send() {
socket.send(input.value);
input.value = "";
}
</script>

0 comments on commit dadc4b9

Please sign in to comment.