[Go language] WebSocket Usage Demo

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

HTML section

Place a button and a text box on the Web page that is used to send information to the server, which is used to display messages returned from the server.

<! DOCTYPE html>

WebSocket Part

Window.onload = Main;var ws;function main () {    var obtn = document.getElementById (' btn1 ');    Obtn.onclick = OnButton1;} function OnButton1 () {    ws = new WebSocket (' Ws://localhost/ws ');    Ws.onopen = OnOpen;    Ws.onmessage = OnMessage;} function OnOpen (event) {    ws.send (' Hello WebSocket ');} function OnMessage (event) {    var otxt = document.getElementById (' txt1 ');    Otxt.value = Event.data;};

Back-end Section

To handle WebSocket requests, you must have a

Func (*websocket. Conn)
Types of processing functions, such as:

Func onwebsocket (ws *websocket. Conn) {defer ws. Close () var err errorvar str stringfor {if err = WebSocket. Message.receive (WS, &STR); Err! = Nil {break} else {fmt. Println ("Received from client:", str)}str = "Hello, I ' m server." If Err = WebSocket. Message.send (WS, STR); Err! = Nil {break} else {fmt. Println ("Send to Client:", str)}}}

Then correspond with a URL:

http. Handle ("/ws", WebSocket. Handler (Onwebsocket))

The complete code is as follows:

Package Mainimport ("bytes" "Errors" "FMT" "Html/template" "Net/http" "Runtime" "Golang.org/x/net/websocket")//Port const (Http_port string = "Https_port string =" 443 ")//directory const (Css_client_path ="/css/"Dart_client_path ="/js/"Image_ Client_path = "/image/" Css_svr_path = "web" Dart_svr_path = "web" Image_svr_path = "web") Func init () {runtime. Gomaxprocs (runtime. NUMCPU ())}func main () {//the CSS and Scripting Services go to HTTP first. Handle (Css_client_path, HTTP. Fileserver (http. Dir (Css_svr_path))) HTTP. Handle (Dart_client_path, HTTP. Fileserver (http. Dir (Dart_svr_path))//URL corresponds to the processing logic HTTP. Handlefunc ("/", homepage) http. Handle ("/ws", WebSocket. Handler (Onwebsocket))//start service ERR: = http. Listenandserve (":" +http_port, nil) if err! = Nil {fmt. Println ("Service failed//", err)}}func Writetemplatetohttpresponse (res http. Responsewriter, T *template. Template) Error {if T = = Nil | | res = = NIL {return errors. New ("Writetemplatetohttpresponse:t must not being nil.")} var buf bytes. Buffererr: = T.execute (&buf, nil) if err! = Nil {return err}res. Header (). Set ("Content-type", "text/html; Charset=utf-8 ") _, Err = Res. Write (BUF. Bytes ()) Return Err}func homepage (res http. Responsewriter, req *http. Request) {T, err: = template. Parsefiles ("web/loli.html") if err! = Nil {fmt. PRINTLN (err) Return}err = Writetemplatetohttpresponse (res, t) if err! = Nil {fmt. PRINTLN (Err) return}}func onwebsocket (ws *websocket. Conn) {defer ws. Close () var err errorvar str stringfor {if err = WebSocket. Message.receive (WS, &AMP;STR); Err! = Nil {break} else {fmt. Println ("Received from client:", str)}str = "Hello, I ' m server." If Err = WebSocket. Message.send (WS, STR); Err! = Nil {break} else {fmt. Println ("Send to Client:", str)}}}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.