This is a creation in Article, where the information may have evolved or changed.
First get the WebSocket package, at the time of acquisition as if need to download what HG of a software can be executed successfully
Go get Code.google.com/p/go.net/websocket
Step into the chase
Service side:
Import ("Code.google.com/p/go.net/websocket" "FMT" "Log" "Net/http") Func main () {FMT. Println("Start App") HTTP. Handle("/", WebSocket. Handler(Echo)) If err: = http. Listenandserve(": 4001", nil); Err! = Nil {Log. Fatal("Listenandserve:", err)}}func Echo (ws *websocket. Conn) {var err error for {var reply string if Err = WebSocket. Message. Receive(WS, &reply); Err! = Nil {Fmt. Println("Can ' t receive") Break} FMT. Println("Received Back from client:"+ Reply) Msg: ="Received:"+ Reply FMT. Println("Sending to client:"+ msg +"_server") If Err = WebSocket. Message. Send(WS, msg+"_server"); Err! = Nil {Fmt. Println("Can ' t send") Break} }}
Client:
<html><head></head><body><script type="Text/javascript"> varSock =NULL;varWsuri ="ws://127.0.0.1:4001"; Window.onload = function() {Console.log ("onload"); Sock =NewWebSocket (Wsuri); Sock.onopen = function() {Console.log ("Connected to"+ Wsuri); } Sock.onclose = function(e) {Console.log ("Connection closed ("+ E.code +")"); } sock.onmessage = function(e) {Console.log ("message Received:"+ E.data); } }; function send() { varmsg = document.getElementById (' message '). Value; Sock.send (msg); }</script><H1>WebSocket Echo Test</H1><form> <p>Message:<input id="message" type="text" value="Hello, world! " ></P></form><button onclick="Send ();" >Send Message</button></body></html>
Start the server and display the start app successfully
When the client sends the information entered by the user, the server receives the corresponding message via receive, and the reply is sent via send.
Page information:
After the client sends the message, the server outputs:
Client output after client sends information:
I hope we can help!