Create the SocketIO Client

Video Lecture

Create the SocketIO Client Create the SocketIO Client Create the SocketIO Client

Description

First create a html file called index.html in the dist/client folder and add this html

dist/client/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<!DOCTYPE html>
<html>

<head>
    <title>TypeScript Socket.IO Course</title>
</head>

<body>
    <script src="socket.io/socket.io.js"></script>
    <script>
        var socket = io();
    </script>
</body>

</html>

Install express and it's types

1
2
npm install express
npm install @types/express

src/server/server.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import express from "express"
import path from "path"
import http from "http"
import socketIO from "socket.io"

const port: number = 3000

class App {
    private server: http.Server
    private port: number

    constructor(port: number) {
        this.port = port

        const app = express()
        app.use(express.static(path.join(__dirname, '../client')))

        this.server = new http.Server(app);
        const io: socketIO.Server = socketIO(this.server);
    }

    public Start() {
        this.server.listen(this.port, () => {
            console.log( `Server listening on port ${this.port}.` )
        })
    }
}

new App(port).Start()

Visit

http://127.0.0.1:3000

Server Options

https://socket.io/docs/server-api/#new-Server-httpServer-options

Download Client JavaScript from a CDN

1
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js" integrity="sha256-bQmrZe4yPnQrLTY+1gYylfNMBuGfnT/HKsCGX+9Xuqo=" crossorigin="anonymous"></script>