Blame view

wave/server_6000.js 2.05 KB
cf76164e6   Ting Chan   20190709
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
  var http = require("http");
  var url = require('url');
  var fs = require('fs');
  var io = require('socket.io'); // 加入 Socket.IO
  
  var server = http.createServer(function(request, response) {
  
    console.log('Connection');
    var path = url.parse(request.url).pathname;
    
    switch (path) {
      case '/':
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write('Hello, World.');
        response.end();
        break;
      case '/earthquake.html':
        fs.readFile(__dirname + path, function(error, data) {
          if (error){
            response.writeHead(404);
            response.write("opps this doesn't exist - 404");
          } else {
            response.writeHead(200, {"Content-Type": "text/html"});
            response.write(data, "utf8");
          }
          response.end();
        });
        break;
      default:
        response.writeHead(404);
        response.write("opps this doesn't exist - 404");
        response.end();
        break;
    }
  });
  
  server.listen(10200);
  io.listen(server);  // 開啟 Socket.IO 的 listener 
  
  
  
  var serv_io = io.listen(server);
  
  net = require('net');
  
  // Keep track of the chat clients
  var clients = [];
  
  // Start a TCP Server
  net.createServer(function (socket) {
  
   
    // Put this new client in the list
    clients.push(socket);
    socket.on('data', function (data) {
      broadcast(data, socket);
  	var aa = data.toString('utf8');
  	if(aa != '0 -1,'){
  		serv_io.emit('date', {'date': aa});
  	}
    });
    
    
  	socket.on('close', function() {
  		var i = clients.indexOf(socket);
  		delete clients[i];
  	});
  }).listen(6000);
  
  
  	function readTextFile()
  	{
  		fs.readFile('a.txt', 'utf8', function(err, data) {  
  			if (err) throw err;
  			return data.toString();
  		});
  	}
  	
  
  
  // Send a message to all clients
    function broadcast(message, sender) {
      clients.forEach(function (client) {
        // Don't want to send it to sender
        if (client === sender) return;
        client.write(message);
      });
      // Log it to the server output too
      process.stdout.write(message)
    }