a chat room
parent
c9c4800d68
commit
13b583a77e
2
go.mod
2
go.mod
|
|
@ -6,3 +6,5 @@ require (
|
|||
github.com/gorilla/websocket v1.5.3
|
||||
golang.org/x/time v0.14.0
|
||||
)
|
||||
|
||||
require github.com/google/uuid v1.6.0 // indirect
|
||||
|
|
|
|||
2
go.sum
2
go.sum
|
|
@ -1,3 +1,5 @@
|
|||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
|
|
|
|||
|
|
@ -1,77 +1,55 @@
|
|||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<script>
|
||||
window.addEventListener("load", function(evt) {
|
||||
|
||||
var output = document.getElementById("output");
|
||||
var input = document.getElementById("input");
|
||||
var ws;
|
||||
|
||||
var print = function(message) {
|
||||
var d = document.createElement("div");
|
||||
d.textContent = message;
|
||||
output.appendChild(d);
|
||||
output.scroll(0, output.scrollHeight);
|
||||
};
|
||||
|
||||
document.getElementById("open").onclick = function(evt) {
|
||||
if (ws) {
|
||||
return false;
|
||||
}
|
||||
ws = new WebSocket("ws://"+window.location.host+"/ws");
|
||||
ws.onopen = function(evt) {
|
||||
print("OPEN");
|
||||
}
|
||||
ws.onclose = function(evt) {
|
||||
print("CLOSE");
|
||||
ws = null;
|
||||
}
|
||||
ws.onmessage = function(evt) {
|
||||
print("RESPONSE: " + evt.data);
|
||||
}
|
||||
ws.onerror = function(evt) {
|
||||
print("ERROR: " + evt.data);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
document.getElementById("send").onclick = function(evt) {
|
||||
if (!ws) {
|
||||
return false;
|
||||
}
|
||||
print("SEND: " + input.value);
|
||||
ws.send(input.value);
|
||||
return false;
|
||||
};
|
||||
|
||||
document.getElementById("close").onclick = function(evt) {
|
||||
if (!ws) {
|
||||
return false;
|
||||
}
|
||||
ws.close();
|
||||
return false;
|
||||
};
|
||||
|
||||
});
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<table>
|
||||
<tr><td valign="top" width="50%">
|
||||
<p>Click "Open" to create a connection to the server,
|
||||
"Send" to send a message to the server and "Close" to close the connection.
|
||||
You can change the message and send multiple times.
|
||||
<p>
|
||||
<form>
|
||||
<button id="open">Open</button>
|
||||
<button id="close">Close</button>
|
||||
<p><input id="input" type="text" value="Hello world!">
|
||||
<button id="send">Send</button>
|
||||
</form>
|
||||
</td><td valign="top" width="50%">
|
||||
<div id="output" style="max-height: 70vh;overflow-y: scroll;"></div>
|
||||
</td></tr></table>
|
||||
</body>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<script>
|
||||
window.addEventListener("load", function(evt) {
|
||||
var output = document.getElementById("output");
|
||||
var input = document.getElementById("input");
|
||||
var ws;
|
||||
|
||||
var print = function(message) {
|
||||
var d = document.createElement("div");
|
||||
d.textContent = message;
|
||||
output.appendChild(d);
|
||||
output.scroll(0, output.scrollHeight);
|
||||
};
|
||||
|
||||
ws = new WebSocket("ws://"+window.location.host+"/ws");
|
||||
ws.onopen = function(evt) {
|
||||
print("OPEN");
|
||||
}
|
||||
ws.onclose = function(evt) {
|
||||
print("CLOSE");
|
||||
ws = null;
|
||||
}
|
||||
ws.onmessage = function(evt) {
|
||||
print("RESPONSE: " + evt.data);
|
||||
}
|
||||
ws.onerror = function(evt) {
|
||||
print("ERROR: " + evt.data);
|
||||
}
|
||||
|
||||
document.getElementById("send").onclick = function(evt) {
|
||||
if (!ws || !input.value) {
|
||||
return false;
|
||||
}
|
||||
ws.send(JSON.stringify({
|
||||
"text": input.value
|
||||
}));
|
||||
input.value = "";
|
||||
return false;
|
||||
};
|
||||
});
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div style="width: 80%; height: 80%; margin: auto; display: flex; flex-direction: row;">
|
||||
<form style="flex-grow: 1;">
|
||||
<p><input id="input" type="text" value="" autofocus>
|
||||
<button id="send">Send</button>
|
||||
</form>
|
||||
<div id="output" style="flex-grow: 1; overflow-y: scroll;"></div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
package server
|
||||
|
||||
type message struct {
|
||||
Text string
|
||||
}
|
||||
|
|
@ -5,13 +5,15 @@ import (
|
|||
"net/http"
|
||||
)
|
||||
|
||||
type Server struct{}
|
||||
|
||||
func NewServer() Server {
|
||||
return Server{}
|
||||
type Server struct {
|
||||
sessions []*session
|
||||
}
|
||||
|
||||
func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
func NewServer() *Server {
|
||||
return &Server{}
|
||||
}
|
||||
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/ws":
|
||||
if err := s.WS(w, r); err != nil {
|
||||
|
|
@ -22,12 +24,35 @@ func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
}
|
||||
|
||||
func (s Server) WS(w http.ResponseWriter, r *http.Request) error {
|
||||
sess, err := newSession(w, r)
|
||||
func (s *Server) WS(w http.ResponseWriter, r *http.Request) error {
|
||||
sess, err := newSession(w, r, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sess.Close()
|
||||
|
||||
sess.cb = func(m message) error {
|
||||
log.Printf("cbing to all other sessions %+v", m)
|
||||
for i := range s.sessions {
|
||||
if s.sessions[i].id != sess.id {
|
||||
select {
|
||||
case s.sessions[i].scatterc <- m:
|
||||
case <-s.sessions[i].ctx.Done():
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
s.sessions = append(s.sessions, sess)
|
||||
defer func() {
|
||||
for i := range s.sessions {
|
||||
if s.sessions[i].id == sess.id {
|
||||
s.sessions = append(s.sessions[:i], s.sessions[i+1:]...)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return sess.Run()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,30 +2,38 @@ package server
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/websocket"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
type session struct {
|
||||
ctx context.Context
|
||||
can context.CancelFunc
|
||||
ws *websocket.Conn
|
||||
wg sync.WaitGroup
|
||||
ctx context.Context
|
||||
can context.CancelFunc
|
||||
ws *websocket.Conn
|
||||
wg sync.WaitGroup
|
||||
cb func(message) error
|
||||
id string
|
||||
scatterc chan (message)
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{}
|
||||
|
||||
func newSession(w http.ResponseWriter, r *http.Request) (*session, error) {
|
||||
func newSession(w http.ResponseWriter, r *http.Request, cb func(message) error) (*session, error) {
|
||||
c, err := upgrader.Upgrade(w, r, nil)
|
||||
ctx, can := context.WithCancel(r.Context())
|
||||
return &session{
|
||||
ctx: ctx,
|
||||
can: can,
|
||||
ws: c,
|
||||
ctx: ctx,
|
||||
can: can,
|
||||
ws: c,
|
||||
cb: cb,
|
||||
id: uuid.New().String(),
|
||||
scatterc: make(chan message, 20),
|
||||
}, err
|
||||
}
|
||||
|
||||
|
|
@ -50,18 +58,33 @@ func (s *session) Run() error {
|
|||
|
||||
func (s *session) gather() {
|
||||
s.while(func() error {
|
||||
mt, message, err := s.ws.ReadMessage()
|
||||
mt, msg, err := s.ws.ReadMessage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Println(" read:", mt, message) // TODO
|
||||
return nil
|
||||
if mt != 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
var m message
|
||||
if err := json.Unmarshal(msg, &m); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
log.Printf("gathered %+v", m)
|
||||
return s.cb(m)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *session) scatter() {
|
||||
s.while(func() error {
|
||||
return s.ws.WriteMessage(1, []byte("message")) // TODO
|
||||
select {
|
||||
case m := <-s.scatterc:
|
||||
log.Printf("scattering %+v", m)
|
||||
return s.ws.WriteMessage(1, []byte(m.Text))
|
||||
case <-s.ctx.Done():
|
||||
return s.ctx.Err()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue