introduction to websockets-socket.io

i

So we already know about how http methods work. We even build our own server. But one thing I haven’t talked for a quite while is this thing called websockets.

Lets say you’re using facebook, and you just happens to recieve a notification or a message. But how does that work?

At first you might think like, “we already know how this works! The server just sends a http response to the client. And we get that notification”. But NO. Thats now how that works. We haven’t talked about 1 main things so far.

  • servers won’t remember you just because you send HTTP request. To be honest once the server gives you a response, it won’t remember you again.

So lets say you requested /home and server responds with a html. Thats it. The server has no way to remember to send a data to you, when you get a new message.

websockets

So here comes the web sockets!

WebSockets are upgraded HTTP connections that live until the connection is killed by either the client or the server. 

And we’re gonna build our own web sockets by using socket.io library. https://github.com/googollee/go-socket.io

Basic example

First create a basic go program with main

package main

import (
	"fmt"
)

func main() {
	fmt.Println("hi")
}
  • go get the socket.io package
go get github.com/googollee/go-socket.io
  • import it
socketio "github.com/googollee/go-socket.io"

Now create a basic http server.

package main

import (

	"log"
	"net/http"

)

func main() {

	fs := http.FileServer(http.Dir("static"))
	http.Handle("/", fs)

	log.Println("Serving at localhost:8000...")
	log.Fatal(http.ListenAndServe(":8000", nil))
}

Our project structure looks like this:

The code is pretty much explanatory. We’re gonna serve index.html for / route.

write this in index.html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>Go WebSocket</title>
	</head>
	<body>
		<h2>Hello World</h2>
	</body>
</html>

Once we go to localhost:8000, we see this

Yeah so far, we already know this. But lets add socket.io to it

Create a socket server and pass it to '/socket.io/' route

server, err := socketio.NewServer(nil)

http.Handle("/socket.io/", server)

We successfully added socket.io onto our server. But now lets use it.

When people connected server.OnConnect executes. And the same goes for server.OnDisconnect when people disconnects.

server.OnConnect("/", func(s socketio.Conn) error {
		noOfConnections ++
		s.SetContext("")
		fmt.Println("connected:", noOfConnections)
	
		return nil
	})


	server.OnDisconnect("/", func(s socketio.Conn, reason string) {
		noOfConnections --
		fmt.Println("closed", reason)
		fmt.Println("connected:", noOfConnections)
	})

And don’t forget to start the server. and also properly close it.

go server.Serve()
defer server.Close()

Here’s the full code

package main

import (
	"fmt"
	"log"
	"net/http"

	socketio "github.com/googollee/go-socket.io"
)

func main() {
	noOfConnections := 0

	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}

	server.OnConnect("/", func(s socketio.Conn) error {
		noOfConnections ++
		s.SetContext("")
		fmt.Println("connected:", noOfConnections)
	
		return nil
	})


	server.OnDisconnect("/", func(s socketio.Conn, reason string) {
		noOfConnections --
		fmt.Println("closed", reason)
		fmt.Println("connected:", noOfConnections)
	})

	go server.Serve()
	defer server.Close()

	http.Handle("/socket.io/", server)

	fs := http.FileServer(http.Dir("static"))
	http.Handle("/", fs)

	log.Println("Serving at localhost:8000...")
	log.Fatal(http.ListenAndServe(":8000", nil))
}

I just added a variable noOfConnections and set it to 0. and it increments when people connects and decrements when people disconnects.

Wait but what about the client side?

To use socket.io in the client side, use cdn! https://cdnjs.com/libraries/socket.io

Here’s the html code.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>Go WebSocket</title>
	</head>
	<body>
		<h2>Hello World</h2>
		https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js
		<script>
			const socket = io('http://localhost:8000/socket.io/')
		</script>
	</body>
</html>

Now run the code.

go to localhost:8000

check the terminal again.

close the tab and check it again

Now we know that we properly setted up socket.io. And no we can track how many people watches our website.

Thats it for now.

happy coding

About the author

vigneshwar

Add comment

Leave a Reply

By vigneshwar

Most common tags

%d bloggers like this: