Skip to content

Commit 9411f11

Browse files
committed
use websocket
1 parent c6a718c commit 9411f11

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

main.go

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
package main
22

33
import (
4-
// "code.google.com/p/go.net/websocket"
54
"flag"
65
"fmt"
6+
"github.com/jijinggang/go-websocket"
77
"github.com/jijinggang/goutil"
88
"html/template"
99
"io"
@@ -23,18 +23,17 @@ func showCmdListPage(w http.ResponseWriter, req *http.Request) {
2323
tmpl.Execute(w, _config.Cmds)
2424
}
2525

26-
/*
2726
func showCmdResultInitPage(w http.ResponseWriter, req *http.Request) {
2827
id := req.FormValue("id")
2928
html := strings.Replace(_html, "{id}", id, -1)
3029
io.WriteString(w, html)
31-
}*/
30+
}
3231

3332
func writeString(w io.Writer, str string) {
3433
w.Write([]byte(str))
3534
}
3635

37-
func exec_cmd(id int, w io.Writer) {
36+
func exec_cmd(id int, w *websocket.Conn) {
3837
cmdCfg := &_config.Cmds[id]
3938
if cmdCfg.Running {
4039
writeString(w, "The script is running, please waitting .......")
@@ -74,13 +73,16 @@ func exec_cmd(id int, w io.Writer) {
7473

7574
}
7675

77-
func execAndRefreshCmdResult(w http.ResponseWriter, req *http.Request) {
76+
func execAndRefreshCmdResult(ws *websocket.Conn) {
77+
req := ws.Request()
7878
id, _ := strconv.Atoi(req.FormValue("id"))
7979
if id >= len(_config.Cmds) {
80-
writeString(w, "Invalid Command.")
80+
writeString(ws, "Invalid Command.")
8181
return
8282
}
83-
exec_cmd(id, w)
83+
84+
//ws.SetWriteDeadline(time.Now().Add(20 * time.Second))
85+
exec_cmd(id, ws)
8486
}
8587

8688
type Cmd struct {
@@ -107,9 +109,8 @@ func main() {
107109
port = _config.Port
108110
_html = strings.Replace(HTML_EXEC, "{port}", strconv.Itoa(port), -1)
109111
http.HandleFunc("/run", showCmdListPage)
110-
//http.HandleFunc("/run/cmd", showCmdResultInitPage)
111-
//http.Handle("/run/cmd", websocket.Handler(execAndRefreshCmdResult))
112-
http.HandleFunc("/run/cmd", execAndRefreshCmdResult)
112+
http.HandleFunc("/run/cmd", showCmdResultInitPage)
113+
http.Handle("/run/exec", websocket.Handler(execAndRefreshCmdResult))
113114
http.Handle("/", http.FileServer(http.Dir(_config.WWWRoot))) //use fileserver directly
114115
fmt.Printf("http://localhost:%d/run\n", port)
115116
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
@@ -140,7 +141,7 @@ function init() {
140141
//ws.send("ok");
141142
};
142143
ws.onmessage = function (e) {
143-
div.innerText = div.innerText + e.data + "\n";
144+
div.innerText = div.innerText + e.data;
144145
};
145146
ws.onclose = function (e) {
146147
// div.innerText = div.innerText + "closed";

0 commit comments

Comments
 (0)