{"id":1766,"date":"2014-12-20T03:09:20","date_gmt":"2014-12-20T03:09:20","guid":{"rendered":"http:\/\/41j.com\/blog\/?p=1766"},"modified":"2015-01-09T10:59:07","modified_gmt":"2015-01-09T10:59:07","slug":"simple-websocket-example-golang","status":"publish","type":"post","link":"https:\/\/41j.com\/blog\/2014\/12\/simple-websocket-example-golang\/","title":{"rendered":"Very Simple Websocket example in golang"},"content":{"rendered":"<p><a href=\"http:\/\/41j.com\/blog\/wp-content\/uploads\/2014\/12\/websocket.png\"><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/41j.com\/blog\/wp-content\/uploads\/2014\/12\/websocket.png\" alt=\"websocket\" width=\"267\" height=\"285\" class=\"aligncenter size-full wp-image-1767\" \/><\/a><\/p>\n<p>UPDATE: I&#8217;d recommend checking out <a href=\"http:\/\/41j.com\/blog\/2014\/12\/gorilla-websockets-golang-simple-websockets-example\/\">Gorilla Websockets<\/a> for golang, the standard library doesn&#8217;t support things like KeepAlive packets making it pretty difficult to use in practice.<\/p>\n<p>This is a simple example of websocket communication in golang. Two files are required the golang go and a index.html file which it will server. Here&#8217;s the golang:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\npackage main\r\n\r\nimport (\r\n\t&quot;code.google.com\/p\/go.net\/websocket&quot;\r\n\t&quot;io&quot;\r\n\t&quot;net\/http&quot;\r\n\t&quot;fmt&quot;\r\n)\r\n\r\nfunc echoHandler(ws *websocket.Conn) {\r\n\r\n  receivedtext := make(&#x5B;]byte, 100)\r\n\r\n   n,err := ws.Read(receivedtext)\r\n\r\n  if err != nil {\r\n    fmt.Printf(&quot;Received: %d bytes\\n&quot;,n)\r\n  }\r\n  \r\n  s := string(receivedtext&#x5B;:n])\r\n  fmt.Printf(&quot;Received: %d bytes: %s\\n&quot;,n,s)\r\n  io.Copy(ws, ws)\r\n  fmt.Printf(&quot;Sent: %s\\n&quot;,s)\r\n}\r\n\r\nfunc main() {\r\n  http.Handle(&quot;\/echo&quot;, websocket.Handler(echoHandler))\r\n  http.Handle(&quot;\/&quot;, http.FileServer(http.Dir(&quot;.&quot;)))\r\n  err := http.ListenAndServe(&quot;:8080&quot;, nil)\r\n  if err != nil {\r\n    panic(&quot;Error: &quot; + err.Error())\r\n  }\r\n}\r\n<\/pre>\n<p>And here&#8217;s the html, the html file needs to be saved in a file called index.html:<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n&lt;meta charset=&quot;UTF-8&quot; \/&gt;\r\n&lt;script&gt;\r\n\r\n  var serversocket = new WebSocket(&quot;ws:\/\/localhost:8080\/echo&quot;);\r\n\r\n  serversocket.onopen = function() {\r\n    serversocket.send(&quot;Connection init&quot;);\r\n  }\r\n\r\n  \/\/ Write message on receive\r\n  serversocket.onmessage = function(e) {\r\n    document.getElementById('comms').innerHTML += &quot;Received: &quot; + e.data + &quot;&lt;br&gt;&quot;;\r\n  };\r\n\r\n  function senddata() {\r\n     var data = document.getElementById('sendtext').value;\r\n     serversocket.send(data);\r\n     document.getElementById('comms').innerHTML += &quot;Sent: &quot; + data + &quot;&lt;br&gt;&quot;;\r\n  }\r\n\r\n&lt;\/script&gt;\r\n\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n  &lt;input id=&quot;sendtext&quot; type=&quot;text&quot; \/&gt;\r\n  &lt;input type=&quot;button&quot; id=&quot;sendBtn&quot; value=&quot;send&quot; onclick=&quot;senddata()&quot;&gt;&lt;\/input&gt;\r\n\r\n  &lt;div id='comms'&gt;&lt;\/div&gt;\r\n\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>Once created you can run the golang with &#8220;go run main.go&#8221;. And goto localhost:8080 in your web browser to access the test site. If you don&#8217;t already have the library you may also need to download it with &#8220;go get code.google.com\/p\/go.net\/websocket&#8221;.<\/p>\n<h2>UPDATE<\/h2>\n<p>While the above example works, it&#8217;s probably better to keep the socket alive. In the above example the Golang server will keep the socket alive for one read and one write, and then exit. The following example keeps the handler alive in a loop:<\/p>\n<pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\r\npackage main\r\n\r\nimport (\r\n    &quot;golang.org\/x\/net\/websocket&quot;\r\n\/\/    &quot;code.google.com\/p\/go.net\/websocket&quot;\r\n\/\/    &quot;io&quot;\r\n    &quot;net\/http&quot;\r\n    &quot;fmt&quot;\r\n)\r\n\r\nfunc echoHandler(ws *websocket.Conn) {\r\n\r\n  for {\r\n    receivedtext := make(&#x5B;]byte, 100)\r\n\r\n    n,err := ws.Read(receivedtext)\r\n\r\n    if err != nil {\r\n      fmt.Printf(&quot;Received: %d bytes\\n&quot;,n)\r\n    }\r\n\r\n    s := string(receivedtext&#x5B;:n])\r\n    fmt.Printf(&quot;Received: %d bytes: %s\\n&quot;,n,s)\r\n    \/\/io.Copy(ws, ws)\r\n    \/\/fmt.Printf(&quot;Sent: %s\\n&quot;,s)\r\n  }\r\n}\r\n\r\nfunc main() {\r\n  http.Handle(&quot;\/echo&quot;, websocket.Handler(echoHandler))\r\n  http.Handle(&quot;\/&quot;, http.FileServer(http.Dir(&quot;.&quot;)))\r\n  err := http.ListenAndServe(&quot;:8080&quot;, nil)\r\n  if err != nil {\r\n    panic(&quot;Error: &quot; + err.Error())\r\n  }\r\n}\r\n<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>UPDATE: I&#8217;d recommend checking out Gorilla Websockets for golang, the standard library doesn&#8217;t support things like KeepAlive packets making it pretty difficult to use in practice. This is a simple example of websocket communication in golang. Two files are required the golang go and a index.html file which it will server. Here&#8217;s the golang: package [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[1],"tags":[],"class_list":["post-1766","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p1RRoU-su","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/posts\/1766","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/comments?post=1766"}],"version-history":[{"count":6,"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/posts\/1766\/revisions"}],"predecessor-version":[{"id":1905,"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/posts\/1766\/revisions\/1905"}],"wp:attachment":[{"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/media?parent=1766"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/categories?post=1766"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/41j.com\/blog\/wp-json\/wp\/v2\/tags?post=1766"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}