-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebsocket.go
51 lines (44 loc) · 1.02 KB
/
websocket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
"html/template"
"io"
)
func Echo(ws *websocket.Conn) {
var err error
fmt.Println("WS Opening")
for {
fmt.Println("Listening start")
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil {
if err == io.EOF {
fmt.Println("WS Closed")
} else {
fmt.Println("Can't receive")
}
break
}
fmt.Println("Received back from client: " + reply)
msg := "Received: " + reply
fmt.Println("Sending to client: " + msg)
if err = websocket.Message.Send(ws, msg); err != nil {
fmt.Println("Can't send")
break
}
}
}
func chat(w http.ResponseWriter, r*http.Request) {
r.ParseForm()
t,_ := template.ParseFiles("websocket.html")
t.Execute(w, nil)
}
func main(){
http.Handle("/", websocket.Handler(Echo))
http.HandleFunc("/chat", chat)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListentAndServe:", err)
}
}