This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 50
/
server.js
208 lines (179 loc) · 6.92 KB
/
server.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
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
// Copyright (c) 2016 IBM Corp. All rights reserved.
// Use of this source code is governed by the Apache License,
// Version 2.0, a copy of which can be found in the LICENSE file.
var WebSocketServer = require('websocket').server;
var http = require('http');
var serveStatic = require('serve-static')
var finalhandler = require('finalhandler')
var winston = require('winston');
//Ws functions
var sendUnknownType = require('./src/room/sendUnknownType.js');
var prepareChatMessage = require('./src/room/prepareChatMessage.js');
var prepareGoodbyeMessage = require('./src/room/prepareGoodbyeMessage.js');
var sendInventory = require('./src/room/sendInventory.js');
var sendExamine = require('./src/room/sendExamine.js');
var parseGoCommand = require('./src/room/parseGoCommand.js');
var sendUnknownCommand = require('./src/room/sendUnknownCommand.js');
// Room Details
// Your room's name
var theRoomName = (process.env.ROOM_NAME || '');
var fullName = (process.env.FULL_NAME || '');
var description = (process.env.DESCRIPTION || 'This room is filled with little JavaScripts running around everywhere and a monster');
// The environment for the running CF application
var vcapApplication = (process.env.VCAP_APPLICATION || '{}');
// Automatically retrieves the port of your CF
var port = (JSON.parse(vcapApplication).port || 3000);
var appUris = (JSON.parse(vcapApplication).application_uris || ['localhost:'+port]);
var endpointip = appUris[0];
var logger = winston.createLogger({
level: 'debug',
transports: [
new(winston.transports.Console)(),
new(winston.transports.File)({
filename: './access.log'
})
]
});
function logerror (err) {
console.error(err.stack || err.toString())
}
// Serve up public folder
var serve = serveStatic('public')
//Serve up static files (index page & supporting CLI-side JS)
var httpServer = http.createServer(function(req, res) {
if (req.url === '/health') {
res.writeHead(200);
res.end("OK");
} else {
serve(req, res, finalhandler(req, res, {onerror: logerror}));
}
}).listen(port);
//Create websocket
var wsServer = new WebSocketServer({
httpServer: httpServer,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
// Logic to determine if this origin is allowed
// Consider using the secure key generated by Game On! to
// validate that incoming requests are from Game On!
// https://gameontext.gitbooks.io/gameon-gitbook/content/microservices/ApplicationSecurity.html#_signed_requests
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
// Only accept requests from allowed origins
request.reject();
logger.debug("Connection from origin " + request.origin + "rejected.");
return;
};
var conn = request.accept();
conn.on('message', function(message) {
if (message.type === 'utf8') {
var incoming = message.utf8Data;
logger.debug("RECEIVED: " + incoming)
var typeEnd = incoming.indexOf(',')
var targetEnd = incoming.indexOf(',', typeEnd + 1)
var messageType = incoming.substr(0, typeEnd)
console.log("MessageType is " + messageType);
var target = incoming.substr(typeEnd + 1, targetEnd - typeEnd - 1)
var objectStr = incoming.substr(targetEnd + 1)
var object = {}
try {
object = JSON.parse(objectStr)
} catch (err) {
logger.error("Got improper json: " + objectStr)
}
logger.info("Parsed a message of type \"" + messageType + "\" sent to target \"" + target + "\".")
//if (target != theRoomName)
// return
if (messageType === "roomHello") {
logger.debug("In roomHello")
sayHello(conn, object.userId, object.username)
} else if (messageType === "room") {
if (object.content.indexOf('/') == 0) {
parseCommand(conn, object.userId, object.username, object.content)
} else {
logger.info(object.username + " sent chat message \"" + object.content + "\"")
broadcast(prepareChatMessage(conn, object.username, object.content));
}
} else if (messageType === "roomGoodbye") {
logger.debug("Announcing that \"" + object.username + "\" has left the room.")
broadcast(prepareGoodbyeMessage(conn, object.userId, object.username))
} else {
sendUnknownType(conn, object.userId, object.username, messageType, logger);
}
}
});
conn.on("close", function(code, reason) {
logger.debug("Connection closed.")
});
});
// Install a special handler to make sure ctrl-c on the command line stops the container
process.on('SIGINT', function() {
logger.info("The server is exiting");
wsServer.shutDown();
process.exit(0);
});
function parseCommand(conn, target, username, content) {
if (content.substr(1, 3) == "go ") {
parseGoCommand(conn, target, username, content, registration.doors, logger);
}
/*else if (content.substr(1, 5) == "exits")
{
sendExits(conn, target, username)
}
else if (content.substr(1, 4) == "help")
{
sendHelp(conn, target, username)
}
else if (content.substr(1, 9) == "inventory")
{
sendInventory(conn, target, username, logger)
}*/
else if (content.substr(1, 7) == "examine") {
sendExamine(conn, target, username, logger);
} else {
sendUnknownCommand(conn, target, content, logger);
}
}
function sayHello(conn, target, username) {
logger.info("Saying hello to \"" + target + "\"")
var responseObject = {
"type": "location",
"name": theRoomName,
"fullName": fullName,
"description": description,
}
var sendMessageType = "player"
var sendTarget = target
var messageText = sendMessageType + "," +
sendTarget + "," +
JSON.stringify(responseObject)
conn.sendUTF(messageText)
logger.debug("And announcing that \"" + username + "\" has arrived.")
var broadcastMessageType = "player"
var broadcastMessageTarget = "*"
var broadcastMessageObject = {
type: "event",
content: {
"*": username + " enters the room."
},
bookmark: 51
}
var broadcastMessage = broadcastMessageType + "," +
broadcastMessageTarget + "," +
JSON.stringify(broadcastMessageObject)
broadcast(broadcastMessage)
}
function broadcast(message) {
wsServer.connections.forEach(function(conn) {
conn.sendUTF(message)
})
}
process.on('uncaughtException', function(err) {
// handle the error safely
console.log("UNCAUGHT EXCEPTION! " + err)
})
logger.info("The HTTP server is listening on port " + port)
logger.info("The WebSocket server is listening on port " + port)