Skip to content
Browse files

Altered logic so that communications between client and server use JS…

…ON encoded 'message' objects
  • Loading branch information...
1 parent 75e2c49 commit c90ec7f361ad5f22936affab2948599804383345 @matt-west committed Aug 7, 2011
Showing with 51 additions and 8 deletions.
  1. +30 −4 chat.go
  2. +21 −4 index.html
View
34 chat.go
@@ -6,9 +6,11 @@ import (
"log"
"template"
"websocket"
+ "json"
)
var addr = flag.String("addr", ":8080", "http service address")
+var msgCount = 0
func main() {
flag.Parse()
@@ -30,7 +32,8 @@ func webSocketProtocolSwitch(c http.ResponseWriter, req *http.Request) {
}
type message struct {
- text []byte
+ Text string
+ Id int
}
var messageChan = make(chan message)
@@ -50,7 +53,14 @@ func hub() {
conns[subscription.conn] = 0, subscription.subscribe
case message := <-messageChan:
for conn, _ := range conns {
- if _, err := conn.Write(message.text); err != nil {
+ j, err := json.Marshal(message)
+ if err != nil {
+ log.Fatal(err)
+ conn.Close()
+ }
+
+ if _, err := conn.Write(j); err != nil {
+ log.Fatal(err)
conn.Close()
}
}
@@ -67,12 +77,28 @@ func clientHandler(ws *websocket.Conn) {
subscriptionChan <- subscription{ws, true}
for {
- buf := make([]byte, 256)
+ buf := make([]byte, 128)
n, err := ws.Read(buf)
if err != nil {
+ log.Fatal("Reading Buffer: ", err)
+ break
+ }
+
+ //b := []byte(`{"Text": "Hello", "Id": 0}`)
+ log.Print(buf)
+ var m message
+ err = json.Unmarshal(buf[0:n], &m)
+ if err != nil {
+ log.Fatal("Parsing JSON: ", buf, m, err)
break
}
- messageChan <- message{buf[0:n]}
+
+ if m.Text == "{{CMD.NewThread}}" {
+ msgCount++
+ m.Id = msgCount
+ }
+
+ messageChan <- message{m.Text, m.Id}
}
}
View
25 index.html
@@ -30,7 +30,15 @@
if (!msg.val()) {
return false;
}
- conn.send(msg.val());
+
+ var jsonMsg = {
+ "Text" : msg.val(),
+ "Id" : 0
+ };
+
+ var jsonStr = JSON.stringify(jsonMsg);
+
+ conn.send(jsonStr);
return false
});
@@ -42,7 +50,15 @@
return false;
}
msg.val('');
- conn.send('{{CMD.NewThread}}');
+
+ var jsonMsg = {
+ "Text" : "{{CMD.NewThread}}",
+ "Id" : 0
+ };
+
+ var jsonStr = JSON.stringify(jsonMsg);
+
+ conn.send(jsonStr);
return false
});
@@ -53,7 +69,8 @@
appendThread($("<div><b>Connection closed.</b></div>"))
}
conn.onmessage = function(evt) {
- var msg = evt.data;
+ var jsonMsg = JSON.parse(evt.data);
+ var msg = jsonMsg.Text;
if (msg == '{{CMD.NewThread}}') {
// Close the thread
@@ -65,7 +82,7 @@
$('#messages').append('<div class="msg" id="message'+msgCount+'"></div>')
}
- appendThread(evt.data)
+ appendThread(msg)
}
}
} else {

0 comments on commit c90ec7f

Please sign in to comment.
Something went wrong with that request. Please try again.