golangでWebSocketを試してみたいと考え簡単なサンプルを試しました。
client側
lang
1<html> 2<head> 3 <title>websocket sample</title> 4 <script type="text/javascript"> 5 // var wsUri = "ws://echo.websocket.org/"; 6 var wsUri = "ws://localhost:9999/echo"; 7 8 var output; 9 function init() { 10 output = document.getElementById("output"); 11 testWebSocket(); 12 } 13 14 function testWebSocket() { 15 websocket = new WebSocket(wsUri); 16 websocket.onopen = function(evt) { 17 onOpen(evt) 18 }; 19 websocket.onclose = function(evt) { 20 onClose(evt) 21 }; 22 websocket.onmessage = function(evt) { 23 onMessage(evt) 24 }; 25 websocket.onerror = function(evt) { 26 onError(evt) 27 }; 28 } 29 30 function onOpen(evt) { 31 writeToScreen("CONNECTED"); 32 doSend("websocketにメッセージを送信"); 33 } 34 35 function onClose(evt) { 36 37 writeToScreen("DISCONNECTED"); 38 } 39 40 function onMessage(evt) { 41 writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>'); 42 websocket.close(); 43 } 44 45 46 function onError(evt) { 47 writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); 48 } 49 50 function doSend(message) { 51 writeToScreen("SENT: " + message); 52 websocket.send(message); 53 } 54 55 function writeToScreen(message) { 56 var pre = document.createElement("p"); 57 pre.style.wordWrap = "break-word"; 58 pre.innerHTML = message; 59 output.appendChild(pre); 60 } 61 62 window.addEventListener("load", init, false); 63 </script> 64</head> 65<body> 66 67 <h2>WebSocket Test</h2> 68 <div id="output"></div> 69 70</body> 71</html>
server側
lang
1 2package main 3 4import ( 5 "code.google.com/p/go.net/websocket" 6 "fmt" 7 "log" 8 "net/http" 9) 10 11func echoHandler(ws *websocket.Conn) { 12 msg := make([]byte, 512) 13 n, err := ws.Read(msg) 14 if err != nil { 15 log.Fatal(err) 16 } 17 fmt.Printf("Receive: %s\n", msg[:n]) 18 19 m, err := ws.Write(msg[:n]) 20 if err != nil { 21 log.Fatal(err) 22 } 23 fmt.Printf("Send: %s\n", msg[:m]) 24} 25 26func main() { 27 http.Handle("/echo", websocket.Handler(echoHandler)) 28 err := http.ListenAndServe(":9999", nil) 29 if err != nil { 30 panic("ListenAndServe: " + err.Error()) 31 } 32} 33
client側はuriをecho.websocket.orgにするとうまく動きますのでサーバサイドの問題かとも思うのですが
具体的にどこが問題かをご教示いただければ幸いです。
よろしくお願いいたします
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。