Chat サーバーを作ってみた…こぴぺしてみた
main.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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
package main import ( "fmt" "html" "log" "net/http" "time" "golang.org/x/net/websocket" ) var websocketList map[string]*websocket.Conn type message struct { Msg string } func auth(w http.ResponseWriter, req *http.Request) (string, error) { c, err := req.Cookie("X-User") if err != nil { return "", err } user := c.Value if len(user) == 0 { websocket.Handler(func(ws *websocket.Conn) { websocket.JSON.Send(ws, message{"Authentication failed"}) }).ServeHTTP(w, req) return "", fmt.Errorf("Authentication failed") } return user, nil } func main() { log.Println("Start main") websocketList = map[string]*websocket.Conn{} http.Handle("/", http.FileServer(http.Dir("./"))) http.HandleFunc("/chat", func(w http.ResponseWriter, req *http.Request) { user, err := auth(w, req) if err != nil { return } prepared := make(chan bool) go func() { <-prepared sendToEveryone(user + " logged in") }() s := websocket.Server{Handler: func(conn *websocket.Conn) { // Want to know way to get Conn websocketList[user] = conn prepared <- true log.Println("conn.MaxPayloadBytes", conn.MaxPayloadBytes) chatHandler(user, conn) }} s.ServeHTTP(w, req) // blocking... log.Println("--") delete(websocketList, user) }) if err := http.ListenAndServe(":9000", nil); err != nil { panic("ListenAndServe: " + err.Error()) } } func sendToEveryone(msg string) { for _, w := range websocketList { t := time.Now() d := t.Format("Monday Jan 02 15:04:05 JST 2006") // d := t.Format("2006-01-02 15:04:05") // => "2015-05-05 07:53:54" websocket.JSON.Send(w, message{fmt.Sprintf("%s / %s", html.EscapeString(msg), d)}) } } func chatHandler(user string, conn *websocket.Conn) { log.Println("chatHandler") for { var msg message if err := websocket.JSON.Receive(conn, &msg); err != nil { log.Println(err) break } sendToEveryone(user + " ⇒ " + msg.Msg) } } |
websocket.js:
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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
// var wsUri = "ws://localhost:9999/chat"; var wsUri = "ws://" + location.host + "/chat"; var output; var websocket; function init() { output = document.getElementById("output"); } function login() { var user = document.getElementById("user").value; document.cookie = 'X-User=' + user + '; path=/'; websocket = new WebSocket(wsUri); websocket.onopen = function (event) { onOpen(event) }; websocket.onclose = function (event) { onClose(event) }; websocket.onmessage = function (event) { onMessage(event) }; websocket.onerror = function (event) { onError(event) }; } function send() { var msg = document.getElementById("msg").value; // writeToScreen(msg); doSend(msg); } function onOpen(event) { writeToScreen("CONNECTED"); document.getElementById("login").style.display = "none"; document.getElementById("send").style.display = "initial"; } function onClose(event) { // console.log(event); writeToScreen("DISCONNECTED"); writeToScreen('<span style="color: blue;">CLOSE: ' + getWebSocketErrorMessage(event.code) + '</span>'); document.getElementById("login").style.display = "initial"; document.getElementById("send").style.display = "none"; } function onMessage(event) { var jsonData = JSON.parse(event.data) // console.log(jsonData) writeToScreen('<span style="color: black;">' + jsonData.Msg + '</span>'); // websocket.close(); } function onError(event) { // console.log(event); writeToScreen('<span style="color: red;">ERROR:</span>'); } function doSend(message) { var jsonData = { Msg: message, } websocket.send(JSON.stringify(jsonData)); } function writeToScreen(message) { var pre = document.createElement("p"); pre.style.wordWrap = "break-word"; pre.innerHTML = message; // output.appendChild(pre); output.prepend(pre) } // https://stackoverflow.com/questions/18803971/websocket-onerror-how-to-read-error-description function getWebSocketErrorMessage(code) { switch (code) { case 1000: return "Normal closure, meaning that the purpose for which the connection was established has been fulfilled."; case 1001: return "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page."; case 1002: return "An endpoint is terminating the connection due to a protocol error"; case 1003: return "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message)."; case 1004: return "Reserved. The specific meaning might be defined in the future."; case 1005: return "No status code was actually present."; case 1006: return "The connection was closed abnormally, e.g., without sending or receiving a Close control frame"; case 1007: return "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message)."; case 1008: return "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy."; case 1009: return "An endpoint is terminating the connection because it has received a message that is too big for it to process."; case 1010: // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead. return "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason; case 1011: return "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request."; case 1015: return "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified)."; default: return "Unknown reason"; } } window.addEventListener("load", init, false); |
index.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html lang="ja"> <head> <link rel="profile" href="http://gmpg.org/xfn/11" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>WebSocket Test with Golang and Javascript</title> </head> <body> <h2>WebSocket Test with Golang and Javascript</h2> <div id="login"><input id="user" /><button onclick="login()">Join</button></div> <div id="send" style="display: none;"><input id="msg" /><button onclick="send()">Send</button></div> <div id="output"></div> <script type="text/javascript" src="./websocket.js"></script> </body> </html> |
See
- https://qiita.com/m0a/items/f6405bc29073a7609050
-
https://stackoverflow.com/questions/30686655/go-program-throwing-error-cannot-find-package-code-google-com-p-go-net-websocke
-
https://qiita.com/nekozuki_twt/items/82974d54db71ee12a5e7
-
https://ashitani.jp/golangtips/tips_time.html