Skip to content

Commit

Permalink
TypeScript server improvements
Browse files Browse the repository at this point in the history
Slight organization conserns, moving a couple curly braces to the same line to improve readability, etc.
  • Loading branch information
evolutionleo committed Apr 8, 2021
1 parent a50ee07 commit 02bc6e6
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 108 deletions.
62 changes: 62 additions & 0 deletions TypescriptServer/src/custom_stuff.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Please edit this file
import { Socket } from 'net';
import { Data, packet } from './networking'
import { clients } from './globals'

export function handlePacket(c: Client, data: Data):void {
var cmd = data.cmd.toLowerCase();

switch(cmd) {
case 'hello':
console.log("Hello from client: " + data.kappa);
c.sendHello();
break;
case 'message':
console.log('Message from client: ' + data.msg);
c.sendMessage(data.msg + ' indeed');
break;
// Add your commands here:
// case 'yourcommand':
// // some code
// break;
}
}


export class Client {
socket: Socket;
username: string; // todo: implement actual usernames

constructor(socket: Socket) {
this.socket = socket;

this.username = undefined;
this.socket = socket;
// you can add more variables here
}

// these 2 functions are internal,
write(data: Data):void {
this.socket.write(packet.build(data));
}

broadcastAll(data: Data):void {
clients.forEach(c => {
c.write(data);
});
}
// you might want to implement a broadcastLobby() if you have those


// Custom Wrappers
sendHello():void {
this.write({ cmd: 'hello', str: 'Hello, client' });
}

sendMessage(msg: string):void {
this.write({ cmd: 'message', msg: msg });
}
// feel free to add more below


}
5 changes: 5 additions & 0 deletions TypescriptServer/src/globals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// here you can put any global variables to later import
// (for access across files)
import { Client } from './custom_stuff'

export var clients:Client[] = [];
77 changes: 7 additions & 70 deletions TypescriptServer/src/networking.ts
Original file line number Diff line number Diff line change
@@ -1,75 +1,13 @@
// this file contains internal things that you shouldn't touch (unless you know what you're doing)
import { Socket } from 'net'
import { Client, handlePacket } from './custom_stuff'
import { encode, decode } from '@msgpack/msgpack'

export type Data = { [key: string]: string; };
// theoretically you can make it any type, but anything other than a map makes little sense
export type Data = { [key: string]: any; cmd: string; };

export function handlePacket(c: Client, data: Data): void
{
var cmd = data.cmd.toLowerCase();

switch(cmd)
{
case 'hello':
console.log("Hello from client: " + data.kappa);
c.sendHello();
break;
case 'message':
console.log('Message from client: ' + data.msg);
c.sendMessage(data.msg + ' indeed');
break;
// Add your commands here:
}
}

export class Client
{
socket: Socket;
username: string;

//#region Necessary Functions

constructor(socket: Socket)
{
this.socket = socket;

this.username = undefined;
this.socket = socket;
// you can add more variables here
}

write(data: Data): void
{
this.socket.write(packet.build(data));
}

broadcastAll(data: Data, clients: Client[]): void
{
clients.forEach(
c =>
{
c.write(data);
}
);
}
//#endregion

//#region Wrappers
sendHello(): void
{
this.write({ cmd: 'hello', str: 'Hello, client' });
}

sendMessage(msg: string): void
{
this.write({ cmd: 'message', msg: msg });
}
//#endregion
}

export let packet =
{
build: (data: Data): Buffer =>
{
export let packet = {
build: function(data: Data):Buffer {
var dataBuff = encode(data);
var sizeBuff = Buffer.alloc(2);
sizeBuff.writeUInt16LE(dataBuff.length);
Expand All @@ -78,8 +16,7 @@ export let packet =
return buff;
},

parse: (c: Client, data: any): void =>
{
parse: function(c: Client, data: any):void {
var dataSize = data.length;
for(var i = 0; i < dataSize;)
{
Expand Down
60 changes: 22 additions & 38 deletions TypescriptServer/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,31 @@ import * as net from 'net';

const port = 1338;

// Unnecessary complexity
//import { handlePacket } from './custom/handlePacket';
//import { Clients } from './static/clients';
//import { packet } from './static/packet'; // packet = { parse(), build() }
import { Client, Data, handlePacket, packet } from './networking'; // class Client {...}
import { Client, handlePacket } from './custom_stuff'
import { Data, packet } from './networking';
import { clients } from './globals';

let clients: Client[] = []; //No need for a single file
const server = net.createServer(socket => {
console.log("Socket connected!");

var c = new Client(socket);
c.username = ""; // todo: implement actual nicknames

clients.push(c); // unnecessary, but useful if you want to iterate over all clients

const server = net.createServer(
socket =>
{
console.log("Socket connected!");

var c = new Client(socket);
c.username = ""; // todo: implement actual nicknames

clients.push(c); // add the client to clients list (unnecessary)
// Bind functions on events
socket.on('error', (err) => {
console.log(`Error! ${err}`); // Don't crash the server on error
});

socket.on('data', (data) => {
packet.parse(c, data); // Handle data
});

// Bind functions on events
socket.on('error',
err =>
{
console.log(`Error! ${err}`); // Don't crash on error
}
);

socket.on('data',
data =>
{
packet.parse(c, data); // Do stuff
}
);

socket.on('end',
() =>
{
console.log('Socket ended.');
}
);
}
);
socket.on('end', () => {
console.log('Socket ended.');
});
});

server.listen(port);
console.log("Server running on port " + port + "!");

0 comments on commit 02bc6e6

Please sign in to comment.