mirror of
https://forge.murkfall.net/bluesaxman/deckard-and-company.git
synced 2026-03-13 08:54:20 -06:00
Moved to using websockets
This commit is contained in:
71
Server/server.pl
Executable file
71
Server/server.pl
Executable file
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/perl -w
|
||||
use strict;
|
||||
use warnings;
|
||||
use Net::WebSocket::Server;
|
||||
use JSON;
|
||||
|
||||
my $origin = 'ws://localhost';
|
||||
my %sessions = ();
|
||||
|
||||
sub generateSession {
|
||||
my $newSession = shift;
|
||||
unless (defined $newSession) { $newSession = time; }
|
||||
if ( grep( /$newSession/, keys %sessions ) ) {
|
||||
generateSession();
|
||||
} else {
|
||||
print "Adding session ".$newSession." to database\n";
|
||||
$sessions{$newSession} = ();
|
||||
$sessions{$newSession}{"id"} = $newSession;
|
||||
$sessions{$newSession}{"users"} = [];
|
||||
$sessions{$newSession}{"decks"} = ();
|
||||
$sessions{$newSession}{"pools"} = ();
|
||||
|
||||
}
|
||||
return $newSession;
|
||||
}
|
||||
|
||||
sub joinSession {
|
||||
my ($sessionID, $conn) = @_;
|
||||
print "Connection attempts to use session ".$sessionID."\n";
|
||||
unless ( grep( /$sessionID/, keys %sessions ) ) {
|
||||
print "Session ".$sessionID." does not yet exsist, creating...\n";
|
||||
$sessionID = generateSession($sessionID);
|
||||
}
|
||||
push(@{$sessions{$sessionID}{"users"}}, $conn->{"initHand"}->res->key);
|
||||
$conn->{"currentSession"} = $sessions{$sessionID};
|
||||
print "A client has connected to session: ".$conn->{"currentSession"}{"id"}."\n";
|
||||
}
|
||||
|
||||
Net::WebSocket::Server->new(
|
||||
listen => 8080,
|
||||
on_connect => sub {
|
||||
my ($serv, $conn) = @_;
|
||||
$conn->on(
|
||||
handshake => sub {
|
||||
my ($conn,$handshake) = @_;
|
||||
$conn->{"initHand"} = $handshake;
|
||||
},
|
||||
ready => sub {
|
||||
my ($conn) = @_;
|
||||
#strip the / off of the resource request and then assign just the request to $session
|
||||
my $session = (split("/", $conn->{"initHand"}->req->resource_name))[1];
|
||||
unless ($session) { $conn->send_utf8(generateSession()); $conn->disconnect(); print "Severed client, no session given\n"; }
|
||||
joinSession($session,$conn);
|
||||
#Check for user ID, if none $conn->disconnect("noid",generateUser());
|
||||
},
|
||||
utf8 => sub {
|
||||
my ($conn, $msg) = @_;
|
||||
my $sessionID = $conn->{"currentSession"}{"id"};
|
||||
my $messageData = "";
|
||||
eval { $messageData = from_json($msg) };
|
||||
if ($@) { $conn->send_utf8('{"error":1, "message":"ERROR: Invalid json"}'); return 0;}
|
||||
if ($messageData->{"type"} eq "message") {
|
||||
print "'".$messageData->{"message"}."' sent in session ".$sessionID."\n";
|
||||
for ($conn->server->connections) {
|
||||
if ($_->{"currentSession"}{"id"} == $sessionID) { $_->send_utf8(to_json($messageData)); }
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
)->start;
|
||||
Reference in New Issue
Block a user