2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,3 +1,5 @@
Write a server for a minimal text based chat. People should be able to connect via telnet, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
;Task:
Write a server for a minimal text based chat.
Nov. 31st is an interesting deadline :-) --[[User:Walterpachl|Walterpachl]] ([[User talk:Walterpachl|talk]]) 10:46, 2 November 2013 (UTC)
People should be able to connect via telnet, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
<br><br>

View file

@ -0,0 +1,159 @@
import std.getopt;
import std.socket;
import std.stdio;
import std.string;
struct client {
int pos;
char[] name;
char[] buffer;
Socket socket;
}
void broadcast(client[] connections, size_t self, const char[] message) {
writeln(message);
for (size_t i = 0; i < connections.length; i++) {
if (i == self) continue;
connections[i].socket.send(message);
connections[i].socket.send("\r\n");
}
}
bool registerClient(client[] connections, size_t self) {
for (size_t i = 0; i < connections.length; i++) {
if (i == self) continue;
if (icmp(connections[i].name, connections[self].name) == 0) {
return false;
}
}
return true;
}
void main(string[] args) {
ushort port = 4004;
auto helpInformation = getopt
(
args,
"port|p", "The port to listen to chat clients on [default is 4004]", &port
);
if (helpInformation.helpWanted) {
defaultGetoptPrinter("A simple chat server based on a task in rosettacode.", helpInformation.options);
return;
}
auto listener = new TcpSocket();
assert(listener.isAlive);
listener.blocking = false;
listener.bind(new InternetAddress(port));
listener.listen(10);
writeln("Listening on port: ", port);
enum MAX_CONNECTIONS = 60;
auto socketSet = new SocketSet(MAX_CONNECTIONS + 1);
client[] connections;
while(true) {
socketSet.add(listener);
foreach (con; connections) {
socketSet.add(con.socket);
}
Socket.select(socketSet, null, null);
for (size_t i = 0; i < connections.length; i++) {
if (socketSet.isSet(connections[i].socket)) {
char[1024] buf;
auto datLength = connections[i].socket.receive(buf[]);
if (datLength == Socket.ERROR) {
writeln("Connection error.");
} else if (datLength != 0) {
if (buf[0] == '\n' || buf[0] == '\r') {
if (connections[i].buffer == "/quit") {
connections[i].socket.close();
if (connections[i].name.length > 0) {
writeln("Connection from ", connections[i].name, " closed.");
} else {
writeln("Connection from ", connections[i].socket.remoteAddress(), " closed.");
}
connections[i] = connections[$-1];
connections.length--;
i--;
writeln("\tTotal connections: ", connections.length);
continue;
} else if (connections[i].name.length == 0) {
connections[i].buffer = strip(connections[i].buffer);
if (connections[i].buffer.length > 0) {
connections[i].name = connections[i].buffer;
if (registerClient(connections, i)) {
connections.broadcast(i, "+++ " ~ connections[i].name ~ " arrived +++");
} else {
connections[i].socket.send("Name already registered. Please enter your name: ");
connections[i].name.length = 0;
}
} else {
connections[i].socket.send("A name is required. Please enter your name: ");
}
} else {
connections.broadcast(i, connections[i].name ~ "> " ~ connections[i].buffer);
}
connections[i].buffer.length = 0;
} else {
connections[i].buffer ~= buf[0..datLength];
}
} else {
try {
if (connections[i].name.length > 0) {
writeln("Connection from ", connections[i].name, " closed.");
} else {
writeln("Connection from ", connections[i].socket.remoteAddress(), " closed.");
}
} catch (SocketException) {
writeln("Connection closed.");
}
}
}
}
if (socketSet.isSet(listener)) {
Socket sn = null;
scope(failure) {
writeln("Error accepting");
if (sn) {
sn.close();
}
}
sn = listener.accept();
assert(sn.isAlive);
assert(listener.isAlive);
if (connections.length < MAX_CONNECTIONS) {
client newclient;
writeln("Connection from ", sn.remoteAddress(), " established.");
sn.send("Enter name: ");
newclient.socket = sn;
connections ~= newclient;
writeln("\tTotal connections: ", connections.length);
} else {
writeln("Rejected connection from ", sn.remoteAddress(), "; too many connections.");
sn.close();
assert(!sn.isAlive);
assert(listener.isAlive);
}
}
socketSet.reset();
}
}

View file

@ -34,7 +34,12 @@ func ListenAndServe(addr string) error {
}
log.Println("Listening for connections on", addr)
defer ln.Close()
s := &Server{stop: make(chan bool)}
s := &Server{
add: make(chan *conn),
rem: make(chan string),
msg: make(chan string),
stop: make(chan bool),
}
go s.handleConns()
for {
// TODO use AcceptTCP() so that we can get a TCPConn on which
@ -54,10 +59,6 @@ func ListenAndServe(addr string) error {
// handleConns is run as a go routine to handle adding and removal of
// chat client connections as well as broadcasting messages to them.
func (s *Server) handleConns() {
s.add = make(chan *conn)
s.rem = make(chan string)
s.msg = make(chan string)
// We define the `conns` map here rather than within Server,
// and we use local function literals rather than methods to be
// extra sure that the only place that touches this map is this
@ -167,7 +168,7 @@ func (c *conn) welcome() {
// welcome phase has completed successfully. It reads single lines from
// the client and passes them to the server for broadcast to all chat
// clients (including us).
// Once done, we ask the server to remove our (and close) our connection.
// Once done, we ask the server to remove (and close) our connection.
func (c *conn) readloop() {
for {
msg, err := c.ReadString('\n')

View file

@ -0,0 +1,39 @@
#!/usr/bin/env perl6
react {
my %connections;
whenever IO::Socket::Async.listen('localhost', 4004) -> $conn {
my $name;
$conn.print: "Please enter your name: ";
whenever $conn.Supply.lines -> $message {
if !$name {
if %connections{$message} {
$conn.print: "Name already taken, choose another one: ";
}
else {
$name = $message;
%connections{$name} = $conn;
broadcast "+++ %s arrived +++", $name;
}
}
else {
broadcast "%s> %s", $name, $message;
}
LAST {
broadcast "--- %s left ---", $name;
%connections{$name}:delete;
}
}
}
sub broadcast ($format, $from, *@message) {
my $text = sprintf $format, $from, |@message;
say $text;
for %connections.kv -> $name, $conn {
$conn.print: "$text\n" if $name ne $from;
}
}
}

View file

@ -0,0 +1,108 @@
use 5.010;
use strict;
use warnings;
use threads;
use threads::shared;
use IO::Socket::INET;
use Time::HiRes qw(sleep ualarm);
my $HOST = "localhost";
my $PORT = 4004;
my @open;
my %users : shared;
sub broadcast {
my ($id, $message) = @_;
print "$message\n";
foreach my $i (keys %users) {
if ($i != $id) {
$open[$i]->send("$message\n");
}
}
}
sub sign_in {
my ($conn) = @_;
state $id = 0;
threads->new(
sub {
while (1) {
$conn->send("Please enter your name: ");
$conn->recv(my $name, 1024, 0);
if (defined $name) {
$name = unpack('A*', $name);
if (exists $users{$name}) {
$conn->send("Name entered is already in use.\n");
}
elsif ($name ne '') {
$users{$id} = $name;
broadcast($id, "+++ $name arrived +++");
last;
}
}
}
}
);
++$id;
push @open, $conn;
}
my $server = IO::Socket::INET->new(
Timeout => 0,
LocalPort => $PORT,
Proto => "tcp",
LocalAddr => $HOST,
Blocking => 0,
Listen => 1,
Reuse => 1,
);
local $| = 1;
print "Listening on $HOST:$PORT\n";
while (1) {
my ($conn) = $server->accept;
if (defined($conn)) {
sign_in($conn);
}
foreach my $i (keys %users) {
my $conn = $open[$i];
my $message;
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
ualarm(500);
$conn->recv($message, 1024, 0);
ualarm(0);
};
if ($@ eq "alarm\n") {
next;
}
if (defined($message)) {
if ($message ne '') {
$message = unpack('A*', $message);
broadcast($i, "$users{$i}> $message");
}
else {
broadcast($i, "--- $users{$i} leaves ---");
delete $users{$i};
undef $open[$i];
}
}
}
sleep(0.1);
}