repl.it
@Scoder12/

Socket.io WSS Chat Server

Nodejs

No description

fork
loading
Files
  • index.js
  • chat.log
  • index.html
  • package-lock.json
index.js
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
var app = require('express')();
var fs = require('fs');
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile('/home/runner/index.html');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
// This would clear the file: 
//var writestream = fs.createWriteStream("chat.log", {flags:'w'});
//writestream.write("");
var writestream = fs.createWriteStream("chat.log", {flags:'a'});
writestream.write("---SERVER RESTART---\n");
var readstream = fs.createReadStream("chat.log", {flags:'r'});

io.on('connection', function(socket){
    socket.username = false;
    socket.on("login", function(name){
        if (name.length > 20) {
            socket.emit('haccusation', 'too long')
            console.log("too long");
            socket = null;
        }
        socket.username = name;
        fs.readFile('chat.log', 'utf8', function(err, contents) {
            arr = contents.split("\n");
            for (var i = 0; i < arr.length; i++ ) {
                socket.emit("chat message", arr[i]);
            }
            //socket.emit("chat message", contents);
        });
        msg = "Server: " + name + "connected.  "
        writestream.write(msg = "\n");
        io.emit(msg);
    });
    socket.on('chat message', function(msg){
        console.log('hi');
        if (socket.username == false) {
            socket.emit("haccusation", "null");
            console.log("null name");
            socket.disconnect();
			io.emit('chat message', "someone was kicked for hacking");
        }
        if (msg.length > 100) {
            socket.emit("haccusation", "null");
            console.log("msg length exceeded");
            socket.disconnect();
            return;
        }
        if (msg != "") {
            writestream.write(socket.username + ": " + msg + "\n");
            io.emit('chat message', socket.username + ": " + msg + "\n");
        }
  });
});
node v10.16.0