Skip to content

Add Chat Functionality

Video Lecture

Add Chat Functionality Add Chat Functionality

./src/server/chatMessage.ts

1
2
3
4
type ChatMessage = {
    message: string
    from: string
}

./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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import express from 'express'
import path from 'path'
import http from 'http'
import socketIO from 'socket.io'
import LuckyNumbersGame from './luckyNumbersGame'

const port: number = 3000

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

    private io: socketIO.Server
    private game: LuckyNumbersGame

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

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

        this.server = new http.Server(app)
        this.io = new socketIO.Server(this.server)

        this.game = new LuckyNumbersGame()

        this.io.on('connection', (socket: socketIO.Socket) => {
            console.log('a user connected : ' + socket.id)

            socket.on('disconnect', function () {
                console.log('socket disconnected : ' + socket.id)
            })

            socket.on('chatMessage', function (chatMessage: ChatMessage) {
                socket.broadcast.emit('chatMessage', chatMessage)
            })
        })
    }

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

new App(port).Start()

./src/client/client.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
type ChatMessage = {
    message: string
    from: string
}

class Client {
    private socket: SocketIOClient.Socket

    constructor() {
        this.socket = io()

        this.socket.on('connect', function () {
            console.log('connect')
        })

        this.socket.on('disconnect', function (message: any) {
            console.log('disconnect ' + message)
            location.reload()
        })

        this.socket.on('chatMessage', (chatMessage: ChatMessage) => {
            $('#messages').append(
                "<li><span class='float-right'><span class='circle'>" +
                    chatMessage.from +
                    "</span></span><div class='otherMessage'>" +
                    chatMessage.message +
                    '</div></li>'
            )
            this.scrollChatWindow()
        })

        $(document).ready(() => {
            $('#messageText').keypress((e) => {
                var key = e.which
                if (key == 13) {
                    // the enter key code
                    this.sendMessage()
                    return false
                }
            })
        })
    }

    private scrollChatWindow = () => {
        $('#messages').animate(
            {
                scrollTop: $('#messages li:last-child').position().top,
            },
            500
        )
        setTimeout(() => {
            let messagesLength = $('#messages li')
            if (messagesLength.length > 10) {
                messagesLength.eq(0).remove()
            }
        }, 500)
    }

    public sendMessage() {
        let messageText = $('#messageText').val()
        if (messageText.toString().length > 0) {
            this.socket.emit('chatMessage', <ChatMessage>{
                message: messageText,
                from: 'AB',
            })

            $('#messages').append(
                "<li><span class='float-left'><span class='circle'>AB</span></span><div class='myMessage'>" +
                    messageText +
                    '</div></li>'
            )
            this.scrollChatWindow()

            $('#messageText').val('')
        }
    }

    public showGame(id: number) {
        switch (id) {
            case 0:
                $('#gamePanel1').fadeOut(100)
                $('#gamePanel2').fadeOut(100)
                $('#gamePanel0').delay(100).fadeIn(100)
                break
            case 1:
                $('#gamePanel0').fadeOut(100)
                $('#gamePanel2').fadeOut(100)
                $('#gamePanel1').delay(100).fadeIn(100)
                break
            case 2:
                $('#gamePanel0').fadeOut(100)
                $('#gamePanel1').fadeOut(100)
                $('#gamePanel2').delay(100).fadeIn(100)
                break
        }
    }
}

const client = new Client()

./dist/client/index.html

  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
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>TypeScript Socket.IO Course</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" />

        <style>
            .gamePanel {
                position: relative;
                border: solid 1px gray;
                height: 382px;
                border-radius: 0px 20px 4px 20px;
                box-shadow: 15px 10px #dddddd;
            }

            #gamePanel0 {
                display: block;
                background: linear-gradient(
                    180deg,
                    rgba(195, 112, 34, 0.164) 0%,
                    rgba(156, 200, 105, 0.495) 100%
                );
            }

            #gamePanel1 {
                display: none;
                background: linear-gradient(
                    56deg,
                    rgba(225, 238, 255, 0.492) 0%,
                    rgba(122, 67, 250, 0.495) 100%
                );
            }

            #gamePanel2 {
                display: none;
                background: linear-gradient(
                    56deg,
                    rgba(235, 204, 32, 0.492) 0%,
                    rgba(251, 188, 106, 0.495) 100%
                );
            }

            .chatPanel {
                border: solid 1px gray;
                border-radius: 20px 0px 4px 4px;
                box-shadow: 15px 10px #dddddd;
                background: rgb(34, 193, 195);
                background: linear-gradient(
                    56deg,
                    rgba(34, 193, 195, 0.49193275943189773) 0%,
                    rgba(253, 187, 45, 0.494733879880077) 100%
                );
                position: relative;
            }

            .chatMessageInputDiv {
                position: absolute;
                bottom: 0px;
                width: 100%;
            }

            .messages {
                padding-left: 0;
                overflow: hidden;
                height: 340px;
                margin-bottom: 40px;
            }

            .messages li {
                list-style-type: none;
                margin-bottom: 30px;
                padding: 6px 6px 6px 6px;
                display: block;
            }

            .otherMessage {
                background: #ffcda3;
                border: solid 1px gray;
                margin: 0px 5px 5px 0px;
                float: right;
                padding: 0px 6px 0px 6px;
                border-radius: 10px 10px 0 10px;
            }

            .myMessage {
                background: #1bffbb;
                border: solid 1px gray;
                margin: 0px 5px 5px 5px;
                float: left;
                padding: 0px 6px 0px 6px;
                border-radius: 10px 10px 10px 0;
            }

            .jumbotron {
                margin-top: -40px;
                height: 180px;
            }

            .footer {
                margin-top: 10px;
            }
        </style>
    </head>

    <body>
        <div class="jumbotron text-center" style="margin-bottom:0">
            <h1>Lucky Numbers Mini-Games</h1>
            <p>
                <a href="https://sbcode.net/tssock" target="_blank"
                    >https://sbcode.net/tssock</a
                >
            </p>
        </div>

        <nav class="navbar navbar-expand-sm bg-dark navbar-dark">
            <a class="navbar-brand" href="#">Games</a>
            <button
                class="navbar-toggler"
                type="button"
                data-toggle="collapse"
                data-target="#collapsibleNavbar"
            >
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="collapsibleNavbar">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a
                            class="nav-link"
                            href="#"
                            onclick="client.showGame(0)"
                            >🥉Bronze Game</a
                        >
                    </li>
                    <li class="nav-item">
                        <a
                            class="nav-link"
                            href="#"
                            onclick="client.showGame(1)"
                            >🥈Silver Game</a
                        >
                    </li>
                    <li class="nav-item">
                        <a
                            class="nav-link"
                            href="#"
                            onclick="client.showGame(2)"
                            >🥇Gold Game</a
                        >
                    </li>
                </ul>
            </div>
        </nav>

        <div class="container" style="margin-top:30px">
            <div class="row">
                <div class="col-sm-8">
                    <div class="gamePanel" id="gamePanel0">
                        <h2 id="gameTitle">🥉Bronze Game</h2>
                    </div>
                    <div class="gamePanel" id="gamePanel1">
                        <h2 id="gameTitle">🥈Silver Game</h2>
                    </div>
                    <div class="gamePanel" id="gamePanel2">
                        <h2 id="gameTitle">🥇Gold Game</h2>
                    </div>
                </div>
                <div class="col-sm-4">
                    <div class="chatPanel">
                        <ol id="messages" class="messages"></ol>
                        <div class="chatMessageInputDiv">
                            <div class="input-group">
                                <input
                                    class="form-control width100"
                                    id="messageText"
                                    placeholder="Enter Chat Message"
                                    onkeyup=""
                                />
                                <span class="input-group-btn">
                                    <button
                                        class="btn btn-info"
                                        onclick="client.sendMessage()"
                                    >
                                        Send
                                    </button>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="footer text-center" style="margin-bottom:0">
            This is an example game from the TypeScript SocketIO course at
            <a href="https://sbcode.net/tssock" target="_blank"
                >https://sbcode.net/tssock</a
            >
        </div>

        <script src="jquery/jquery.min.js"></script>
        <script src="bootstrap/js/bootstrap.bundle.min.js"></script>
        <script src="socket.io/socket.io.js"></script>
        <script src="client.js"></script>
    </body>
</html>