Chat server: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Phix}}: wrong tag) |
m (→{{header|Wren}}: Minor tidy) |
||
(4 intermediate revisions by 3 users not shown) | |||
Line 6:
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>
=={{header|Ada}}==
{{libheader|AdaSockets}}
<
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Exceptions; use Ada.Exceptions;
Line 94 ⟶ 93:
Dummy.Start (Incoming_Socket);
end loop;
end Chat_Server;</
=={{header|
==={{header|BaCon}}===
Requires BaCon 4.2 or higher. Clients have to login with an alias and can use the commands 'say' or 'quit'. Notifications are submitted when users enter the chat or leave the chat.
<syntaxhighlight lang="text">DECLARE user$ ASSOC STRING
DECLARE connect ASSOC long
OPEN "localhost:51000" FOR SERVER AS mynet
Line 132:
ENDIF
ENDIF
WEND</
==={{header|Visual Basic .NET}}===
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Module Module1
Class State
Private ReadOnly client As TcpClient
Private ReadOnly sb As New StringBuilder
Public Sub New(name As String, client As TcpClient)
Me.Name = name
Me.client = client
End Sub
Public ReadOnly Property Name As String
Public Sub Send(text As String)
Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text))
client.GetStream().Write(bytes, 0, bytes.Length)
End Sub
End Class
ReadOnly connections As New Dictionary(Of Integer, State)
Dim listen As TcpListener
Dim serverThread As Thread
Sub Main()
listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004)
serverThread = New Thread(New ThreadStart(AddressOf DoListen))
serverThread.Start()
End Sub
Private Sub DoListen()
listen.Start()
Console.WriteLine("Server: Started server")
Do
Console.Write("Server: Waiting...")
Dim client = listen.AcceptTcpClient()
Console.WriteLine(" Connected")
' New thread with client
Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))
clientThread.Start(client)
Loop
End Sub
Private Sub DoClient(client As TcpClient)
Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId)
Dim bytes = Encoding.ASCII.GetBytes("Enter name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
Dim done As Boolean
Dim name As String
Do
If Not client.Connected Then
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort() ' Kill thread
End If
name = Receive(client)
done = True
For Each cl In connections
Dim state = cl.Value
If state.Name = name Then
bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ")
client.GetStream().Write(bytes, 0, bytes.Length)
done = False
End If
Next
Loop While Not done
connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client))
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Broadcast(String.Format("+++ {0} arrived +++", name))
Do
Dim text = Receive(client)
If text = "/quit" Then
Broadcast(String.Format("Connection from {0} closed.", name))
connections.Remove(Thread.CurrentThread.ManagedThreadId)
Console.WriteLine(vbTab & "Total connections: {0}", connections.Count)
Exit Do
End If
If Not client.Connected Then
Exit Do
End If
Broadcast(String.Format("{0}> {1}", name, text))
Loop
Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId)
client.Close()
Thread.CurrentThread.Abort()
End Sub
Private Function Receive(client As TcpClient) As String
Dim sb As New StringBuilder
Do
If client.Available > 0 Then
While client.Available > 0
Dim ch = Chr(client.GetStream.ReadByte())
If ch = vbCr Then
' ignore
Continue While
End If
If ch = vbLf Then
Return sb.ToString()
End If
sb.Append(ch)
End While
' pause
Thread.Sleep(100)
End If
Loop
End Function
Private Sub Broadcast(text As String)
Console.WriteLine(text)
For Each client In connections
If client.Key <> Thread.CurrentThread.ManagedThreadId Then
Dim state = client.Value
state.Send(text)
End If
Next
End Sub
End Module</syntaxhighlight>
=={{header|C}}==
Line 141 ⟶ 278:
A glitch occurs if a connection is made using the Telnet protocol - user names are preceded by garbled text.
<
#include <stdlib.h>
#include <sys/socket.h>
Line 388 ⟶ 525:
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Net.Sockets;
Line 534 ⟶ 670:
}
}
}</
=={{header|CoffeeScript}}==
This is ported from the JavaScript version. The tool js2coffee got me a mostly working version, and then I manually converted JS-style classes to CS "classic-style class" syntax.
<
net = require("net")
sys = require("sys")
Line 647 ⟶ 782:
server = new ChatServer()
</syntaxhighlight>
=={{header|Common Lisp}}==
{{libheader|usocket}}
Line 835 ⟶ 806:
*USER-MANAGER*, or upon an error occurring.
<
(ql:quickload '(:usocket :simple-actors :bordeaux-threads))
Line 1,011 ⟶ 982:
(make-thread #'accept-connections)
</syntaxhighlight>
=={{header|D}}==
<syntaxhighlight lang="d">
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();
}
}
</syntaxhighlight>
=={{header|Erlang}}==
<
-module(chat).
Line 1,078 ⟶ 1,210:
Response -> Response
end.
</syntaxhighlight>
=={{header|Go}}==
This example uses the Go idiom of [http://blog.golang.org/share-memory-by-communicating ''Do not communicate by sharing memory; instead, share memory by communicating'']; there are no explicit locks used, instead Go channels are used to safely synchronize where required.
Line 1,087 ⟶ 1,218:
This example handles the case of one specific client "falling behind" by relying on the underlying TCP stack to do a reasonable job of buffering. Once that buffer fills, a write to the that client's connection will time out and the connection will dropped. Other minor improvements would include enabling TCP keep alives, handling temporary errors from accept, and better logging. Not ideal, but it should be good enough for this example.
<
import (
Line 1,268 ⟶ 1,399:
}
c.server.rem <- c.name
}</
=={{header|Groovy}}==
{{trans|Java}}
<
private int port = 0
private List<Client> clientList = new ArrayList<>()
Line 1,427 ⟶ 1,557:
new ChatServer(port).run()
}
}</
=={{header|Haskell}}==
<
import Network
import System.IO
Line 1,514 ⟶ 1,643:
T.putStrLn "Server started"
newMVar (M.empty) >>= clientLoop server
</syntaxhighlight>
==Icon and {{header|Unicon}}==
This is Unicon-specific:
<
procedure main()
Line 1,545 ⟶ 1,674:
critical mlck: nCons -:= 1
}
end</
=={{header|Java}}==
Line 1,553 ⟶ 1,681:
I think ideally, NIO would be used to select() sockets available/ready for I/O, to eliminate the possibility of a bad connection disrupting the server, but this increases the complexity.
<
import java.net.*;
import java.util.*;
Line 1,705 ⟶ 1,833:
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
{{works with|Node.js}}
<
const EventEmitter = require("events").EventEmitter;
Line 1,856 ⟶ 1,983:
// Start the server!
server = new ChatServer();</
=={{header|Julia}}==
Modified to fit the Rosetta Code task from example code for the WebSockets module written by Leah Hanson.
To test, start the code and use a browser to connect to localhost:8000.
<
using HttpServer
using WebSockets
Line 1,944 ⟶ 2,070:
println("Chat server listening on 8000...")
run(server,8000)
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|Java}}
<
import java.io.IOException
import java.io.InputStreamReader
Line 2,100 ⟶ 2,225:
}
}
}</
=={{header|Nim}}==
<
type
Line 2,144 ⟶ 2,268:
asyncCheck serve()
runForever()</
=={{header|Objeck}}==
<
use System.IO.Net;
use System.Concurrency;
Line 2,257 ⟶ 2,380:
}
}
</syntaxhighlight>
=={{header|Ol}}==
<
(define (timestamp) (syscall 201 "%c"))
Line 2,329 ⟶ 2,451:
(run 8080)
</syntaxhighlight>
{{Out}}
Line 2,384 ⟶ 2,506:
(127.0.0.1 . 55320): see you..
</pre>
=={{header|Perl}}==
{{trans|Python}}
<
use strict;
use warnings;
Line 2,494 ⟶ 2,615:
sleep(0.1);
}</
===Alternate with both read and write queuing===
<
use strict; # http://www.rosettacode.org/wiki/Chat_server
Line 2,575 ⟶ 2,696:
}
}
}</
=={{header|Phix}}==
===server===
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\ChatServer.exw
Line 2,749 ⟶ 2,869:
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<!--</
===client===
<!--<
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\ChatClient.exw
Line 2,993 ⟶ 3,113:
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<!--</
=={{header|PicoLisp}}==
<
(de chat Lst
Line 3,023 ⟶ 3,142:
(tell 'chat "--- " *Name " left ---")
(bye) ) ) )
(wait)</
After starting the above script, connect to the chat server from two terminals:
<pre> Terminal 1 | Terminal 2
Line 3,055 ⟶ 3,174:
| Connection closed.
| $</pre>
=={{header|Prolog}}==
Works with Swi-Prolog as of Jan 2019.
This version will load the server automatically on port 5000, adapt to your needs.
<
chat_server(Port) :-
Line 3,140 ⟶ 3,258:
msg_username_taken('That username is already taken, choose another\n\r').
msg_new_line('\n\r').
msg_by_user('~w> ~w').</
=={{header|Python}}==
<
import socket
Line 3,220 ⟶ 3,337:
time.sleep(.1)
except (SystemExit, KeyboardInterrupt):
break</
=={{header|R}}==
This implementation relies on the new server socket connection type introduced in R 4.0.0.
<syntaxhighlight lang="r">
chat_loop <- function(server, sockets, delay = 0.5) {
repeat {
Line 3,370 ⟶ 3,486:
}
start_chat_server()</
=={{header|Racket}}==
This is a very basic chat server, but it does everything that is needed for this task.
<
#lang racket
Line 3,398 ⟶ 3,513:
(void (thread (λ() (chat-server (tcp-listen 12321)))))
((client (current-input-port) (current-output-port)))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
Line 3,405 ⟶ 3,519:
<div style="display:inline-block">{{trans|Python}}</div> (or at least started out that way)
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku"
my %connections;
Line 3,447 ⟶ 3,561:
}
}
}</
Notes:
Line 3,453 ⟶ 3,567:
* It accepts messages encoded in UTF-8.
* It tokenizes the message streams at newline boundaries (using the <tt>Supply.lines</tt> method), which I think makes the most sense for a chat application.
=={{header|Ruby}}==
<
class ChatServer < GServer
Line 3,523 ⟶ 3,636:
#Turn on informational messages
ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join
</syntaxhighlight>
=={{header|Rust}}==
<
use std::collections::HashMap;
use std::io;
Line 3,623 ⟶ 3,735:
chat_loop(&listener).unwrap();
}
</syntaxhighlight>
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<
# Write a message to everyone except the sender of the message
Line 3,687 ⟶ 3,798:
socket -server {coroutine c[incr count] chat} 4004
set ::cmap {}; # Dictionary mapping nicks to channels
vwait forever; # Run event loop</
=={{header|
An embedded solution using a C host since Wren has no built in support for either networking or multi-threading.
The following is based on the C code [https://github.com/yorickdewid/Chat-Server/blob/master/chat_server.c here] and runs fine on my Ubuntu 20.04 box.
As Wren's VM is single threaded we create separate VMs to service each potential client connection (limited to 10) which run in their own thread. As the only way for the VMs to share mutable state is to use global variables within the host, synchronization is needed when accessing such variables.
<syntaxhighlight lang="wren">/* Chat_server.wren */
class Clients {
foreign static max
foreign static count
foreign static isActive(vmi)
foreign static connfd(vmi)
foreign static uid(vmi)
foreign static name(vmi)
foreign static setName(vmi, s)
foreign static printAddr(vmi)
foreign static delete(vmi)
}
class Mutex {
foreign static clientsLock()
foreign static clientsUnlock()
foreign static topicLock()
foreign static topicUnlock()
}
class Chat {
// send message to all clients but the sender
static sendMessage(s, uid) {
Mutex.clientsLock()
for (i in 0...Clients.max) {
if (Clients.isActive(i) && Clients.uid(i) != uid) {
if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
System.print("Write to descriptor %(Clients.connfd(i)) failed.")
break
}
}
}
Mutex.clientsUnlock()
}
// send message to all clients
static sendMessageAll(s) {
Mutex.clientsLock()
for (i in 0...Clients.max) {
if (Clients.isActive(i)) {
if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
System.print("Write to descriptor %(Clients.connfd(i)) failed.")
break
}
}
}
Mutex.clientsUnlock()
}
// send message to sender
static sendMessageSelf(s, connfd) {
if (write(connfd, s, s.bytes.count) < 0) {
Fiber.abort("Write to descriptor %(connfd) failed.")
}
}
// send message to
static sendMessageClient(s, uid) {
for (i in
if (Clients.isActive(i) && Clients.uid(i) == uid) {
if (write(Clients.connfd(i), s, s.bytes.count) < 0) {
System.print("Write to descriptor %(Clients.connfd(i)) failed.")
break
}
}
}
Mutex.clientsUnlock()
}
// send list of active clients
static sendActiveClients(connfd) {
Mutex.clientsLock()
for (i in 0...Clients.max) {
if (Clients.isActive(i)) {
var s = "<< [%(Clients.uid(i))] %(Clients.name(i))\r\n"
sendMessageSelf(s, connfd)
}
}
Mutex.clientsUnlock()
}
// handle all communication with the
static handleClient(vmi) {
if (!Clients.isActive(vmi)) {
Fiber.abort("The client handled by VM[%(vmi)] is inactive.")
}
var connfd = Clients.connfd(vmi)
var uid = Clients.uid(vmi)
var name = Clients.name(vmi)
System.write("<< accept ")
Clients.printAddr(vmi)
System.print(" referenced by %(uid)")
var buffOut = "<< %(name) has joined\r\n"
sendMessageAll(buffOut)
Mutex.topicLock()
if (topic != "") {
buffOut = "<< topic: %(topic)\r\n"
sendMessageSelf(buffOut, connfd)
}
Mutex.topicUnlock()
sendMessageSelf("<< see /help for assistance\r\n", connfd)
/* receive input from client */
var buffIn = ""
while ((buffIn = read(connfd, bufferSize/2 - 1)) && buffIn.bytes.count > 0) {
buffOut = ""
buffIn = buffIn.trimEnd("\r\n")
/* ignore empty buffer */
if (buffIn == "") continue
var split = buffIn.split(" ")
if (command == "/quit") {
} else if (command == "/topic") {
if (split.count > 0) {
Mutex.topicLock()
topic = split[1..-1].join(" ")
Mutex.topicUnlock()
buffOut = "<< topic changed to: %(topic)\r\n"
sendMessageAll(buffOut)
} else {
sendMessageSelf("<< message cannot be null\r\n", connfd)
}
} else if (command == "/nick") {
if (split.count > 0) {
var newName = split[1..-1].join(" ")
buffOut = "<< %(name) is now known as %(newName)\r\n"
Clients.setName(vmi, newName)
name = newName
sendMessageAll(buffOut)
} else {
sendMessageSelf("<< name cannot be null\r\n", connfd)
}
} else if (command == "/msg") {
if (split.count > 0) {
var toUid = Num.fromString(split[1])
if (split.count > 1) {
buffOut = "[PM][%(name)] "
buffOut = buffOut + split[2..-1].join(" ") + "\r\n"
sendMessageClient(buffOut, toUid)
} else {
sendMessageSelf("<< message cannot be null\r\n", connfd)
}
} else {
sendMessageSelf("<< reference cannot be null\r\n", connfd)
}
} else if (command == "/list") {
buffOut = "<< clients %(Clients.count)\r\n"
sendMessageSelf(buffOut, connfd)
sendActiveClients(connfd)
} else if (command == "/help") {
buffOut = ""
buffOut = buffOut + "<< /quit Quit chatroom\r\n"
buffOut = buffOut + "<< /ping Server test\r\n"
buffOut = buffOut + "<< /topic <message> Set chat topic\r\n"
buffOut = buffOut + "<< /nick <name> Change nickname\r\n"
buffOut = buffOut + "<< /msg <reference> <message> Send private message\r\n"
buffOut = buffOut + "<< /list Show active clients\r\n"
buffOut = buffOut + "<< /help Show help\r\n"
sendMessageSelf(buffOut, connfd)
} else {
sendMessageSelf("<< unknown command\r\n", connfd)
}
} else {
/* send message */
buffOut = "[%(name)] %(buffIn)\r\n"
sendMessage(buffOut, uid)
}
}
/* close connection
buffOut = "<<
sendMessageAll(buffOut)
close(connfd)
/* delete client
System.write("<< quit ")
System.print(" referenced by %(uid)")
Clients.delete(vmi)
}
foreign static topic
foreign static topic=(s)
foreign static
foreign static write(connfd, buf, count)
foreign static read(connfd, count)
foreign static close(connfd)
}</syntaxhighlight>
<br>
We now embed this in the following C program, build and run it to start the server. To end the server, just press control-C. For testing purposes, clients can use telnet from separate terminals to connect to the server on port 5000.
<syntaxhighlight lang="c">/* gcc Chat_server.c -o Chat_server -lpthread -lwren -lm */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <signal.h>
#include <wren.h>
#define MAX_CLIENTS 10
#define BUFFER_SZ 2048
static _Atomic unsigned int cli_count = 0;
static int listenfd = 0, uid = 10;
char *script = NULL;
/* Client structure */
typedef struct {
struct sockaddr_in addr; /* Client remote address */
int connfd; /* Connection file descriptor */
int uid;
int vmi;
char name[32]; /* Client name
} client_t;
client_t *clients[MAX_CLIENTS];
pthread_mutex_t clients_mutex = PTHREAD_MUTEX_INITIALIZER;
static char topic[BUFFER_SZ/2];
pthread_mutex_t topic_mutex = PTHREAD_MUTEX_INITIALIZER;
WrenVM* vms[MAX_CLIENTS]; // array of VMs
/* add client to queue */
void queue_add(client_t *cl){
pthread_mutex_lock(&clients_mutex);
for (int i = 0; i < MAX_CLIENTS; ++i) {
if (!clients[i]) {
cl->vmi = i;
clients[i] = cl;
break;
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* Delete client from queue */
void queue_delete(int uid){
pthread_mutex_lock(&clients_mutex);
for (int i = 0; i < MAX_CLIENTS; ++i) {
if (clients[i]) {
if (clients[i]->uid == uid) {
clients[i] = NULL;
break;
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
/* print ip address */
void print_client_addr(struct sockaddr_in addr){
printf("%d.%d.%d.%d",
addr.sin_addr.s_addr & 0xff,
(addr.sin_addr.s_addr & 0xff00) >> 8,
(addr.sin_addr.s_addr & 0xff0000) >> 16,
(addr.sin_addr.s_addr & 0xff000000) >> 24);
}
/* enable Wren to handle all client communication */
void *handle_client(void *arg) {
client_t *cli = (client_t *)arg;
cli_count++;
int vmi = cli->vmi;
WrenHandle *callHandle = wrenMakeCallHandle(vms[vmi], "handleClient(_)");
wrenEnsureSlots(vms[vmi], 2);
wrenGetVariable(vms[vmi], "main", "Chat", 0);
wrenSetSlotDouble(vms[vmi], 1, (double)vmi);
wrenCall(vms[vmi], callHandle);
}
/* C <= Wren interface functions */
void C_max(WrenVM* vm) {
wrenSetSlotDouble(vm, 0, (double)MAX_CLIENTS);
}
void C_count(WrenVM* vm) {
wrenSetSlotDouble(vm, 0, (double)cli_count);
}
void C_isActive(WrenVM* vm) {
int vmi = (int)wrenGetSlotDouble(vm, 1);
bool res = clients[vmi] != NULL;
wrenSetSlotBool(vm, 0, res);
}
void C_connfd(WrenVM* vm) {
int vmi = (int)wrenGetSlotDouble(vm, 1);
wrenSetSlotDouble(vm, 0, (double)clients[vmi]->connfd);
}
void C_uid(WrenVM* vm) {
int vmi = (int)wrenGetSlotDouble(vm, 1);
wrenSetSlotDouble(vm, 0, (double)clients[vmi]->uid);
}
void C_name(WrenVM* vm) {
int vmi = (int)wrenGetSlotDouble(vm, 1);
wrenSetSlotString(vm, 0, (const char *)clients[vmi]->name);
}
void C_setName(WrenVM* vm) {
int vmi = (int)wrenGetSlotDouble(vm, 1);
const char *name = wrenGetSlotString(vm, 2);
size_t size = sizeof(clients[vmi]->name);
strncpy(clients[vmi]->name, name, size);
clients[vmi]->name[size-1] = '\0';
}
void C_clientsLock(WrenVM* vm) {
pthread_mutex_lock(&clients_mutex);
}
void C_clientsUnlock(WrenVM* vm) {
pthread_mutex_unlock(&clients_mutex);
}
void C_topicLock(WrenVM* vm) {
pthread_mutex_lock(&topic_mutex);
}
void C_topicUnlock(WrenVM* vm) {
pthread_mutex_unlock(&topic_mutex);
}
void C_printAddr(WrenVM* vm) {
int vmi = (int)wrenGetSlotDouble(vm, 1);
print_client_addr(clients[vmi]->addr);
}
void C_topic(WrenVM* vm) {
wrenSetSlotString(vm, 0, (const char *)topic);
}
void C_setTopic(WrenVM* vm) {
const char *t = wrenGetSlotString(vm, 1);
strncpy(topic, t, sizeof(topic));
topic[sizeof(topic)-1] = '\0';
}
void C_bufferSize(WrenVM* vm) {
wrenSetSlotDouble(vm, 0, (double)BUFFER_SZ);
}
void C_write(WrenVM* vm) {
int fd = (int)wrenGetSlotDouble(vm, 1);
const void *buf = (const void *)wrenGetSlotString(vm, 2);
size_t count = (size_t)wrenGetSlotDouble(vm, 3);
ssize_t res = write(fd, buf, count);
wrenSetSlotDouble(vm, 0, (double)res);
}
void C_read(WrenVM* vm) {
char buf[BUFFER_SZ / 2];
int fd = (int)wrenGetSlotDouble(vm, 1);
size_t count = (size_t)wrenGetSlotDouble(vm, 2);
ssize_t rlen = read(fd, buf, count);
buf[rlen] = '\0';
wrenSetSlotString(vm, 0, (const char *)buf);
}
void C_close(WrenVM* vm) {
int connfd = (int)wrenGetSlotDouble(vm, 1);
close(connfd);
}
void C_delete(WrenVM* vm) {
int vmi = (int)wrenGetSlotDouble(vm, 1);
client_t *cli = clients[vmi];
queue_delete(cli->uid);
free(cli);
cli_count--;
pthread_detach(pthread_self());
}
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Clients") == 0) {
if (isStatic && strcmp(signature, "max") == 0) return C_max;
if (isStatic && strcmp(signature, "count") == 0) return C_count;
if (isStatic && strcmp(signature, "isActive(_)") == 0) return C_isActive;
if (isStatic && strcmp(signature, "connfd(_)") == 0) return C_connfd;
if (isStatic && strcmp(signature, "uid(_)") == 0) return C_uid;
if (isStatic && strcmp(signature, "name(_)") == 0) return C_name;
if (isStatic && strcmp(signature, "setName(_,_)") == 0) return C_setName;
if (isStatic && strcmp(signature, "printAddr(_)") == 0) return C_printAddr;
if (isStatic && strcmp(signature, "delete(_)") == 0) return C_delete;
} else if (strcmp(className, "Mutex") == 0) {
if (isStatic && strcmp(signature, "clientsLock()") == 0) return C_clientsLock;
if (isStatic && strcmp(signature, "clientsUnlock()") == 0) return C_clientsUnlock;
if (isStatic && strcmp(signature, "topicLock()") == 0) return C_topicLock;
if (isStatic && strcmp(signature, "topicUnlock()") == 0) return C_topicUnlock;
} else if (strcmp(className, "Chat") == 0) {
if (isStatic && strcmp(signature, "topic") == 0) return C_topic;
if (isStatic && strcmp(signature, "topic=(_)") == 0) return C_setTopic;
if (isStatic && strcmp(signature, "bufferSize") == 0) return C_bufferSize;
if (isStatic && strcmp(signature, "write(_,_,_)") == 0) return C_write;
if (isStatic && strcmp(signature, "read(_,_)") == 0) return C_read;
if (isStatic && strcmp(signature, "close(_)") == 0) return C_close;
}
}
return NULL;
}
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
fread(script, 1, fsize, f);
fclose(f);
script[fsize] = 0;
return script;
}
void catch_ctrl_c(int sig) {
/* clean up and exit */
for (int i = 0; i < MAX_CLIENTS; ++i) {
wrenFreeVM(vms[i]);
if (clients[i]) {
close(clients[i]->connfd);
free(clients[i]);
}
}
close(listenfd);
free(script);
printf("\n<[ SERVER ENDED ]>\n");
exit(EXIT_SUCCESS);
}
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignMethodFn = &bindForeignMethod;
const char* module = "main";
const char* fileName = "Chat_server.wren";
script = readFile(fileName);
/* config the VMs and interpret the script */
for (int i = 0; i < MAX_CLIENTS; ++i) {
vms[i] = wrenNewVM(&config);
wrenInterpret(vms[i], module, script);
}
/* prepare to start the server */
int connfd = 0;
struct sockaddr_in serv_addr;
struct sockaddr_in cli_addr;
pthread_t tid;
/* socket settings */
listenfd = socket(AF_INET, SOCK_STREAM, 0);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
/* ignore pipe signals */
signal(SIGPIPE, SIG_IGN);
/* catch ctrl-c being pressed */
signal(SIGINT, catch_ctrl_c);
/* bind */
if (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
perror("Socket binding failed");
return EXIT_FAILURE;
}
/* listen */
if (listen(listenfd, 10) < 0) {
perror("Socket listening failed");
return EXIT_FAILURE;
}
printf("<[ SERVER STARTED ]>\n");
/* accept clients */
while (1) {
socklen_t clilen = sizeof(cli_addr);
connfd = accept(listenfd, (struct sockaddr*)&cli_addr, &clilen);
/* check if max clients is reached */
if ((cli_count + 1) == MAX_CLIENTS) {
printf("<< max clients reached\n");
printf("<< reject ");
print_client_addr(cli_addr);
printf("\n");
close(connfd);
continue;
}
/* client settings */
client_t *cli = (client_t *)malloc(sizeof(client_t));
cli->addr = cli_addr;
cli->connfd = connfd;
cli->uid = uid++;
sprintf(cli->name, "%d", cli->uid);
/* add client to the queue and fork thread */
queue_add(cli);
pthread_create(&tid, NULL, &handle_client, (void*)cli);
/* reduce CPU usage */
sleep(1);
}
return 0;
}</syntaxhighlight>
=={{header|zkl}}==
{{trans|Python}}
On my Linux box, telnet seems to only want to connect to port 23.
<
var users=Dictionary(); // ( handle:socket, ...)
Line 3,877 ⟶ 4,412:
server:=Network.TCPServerSocket.open(PORT);
println("Listening on %s:%s".fmt(server.hostname,server.port));
server.listen(pipe); // Main event loop </
{{out}}
Start the server:
Line 3,920 ⟶ 4,455:
Connection closed by foreign host.
</pre>
{{omit from|AutoHotkey}}
{{omit from|Lilypond}}
{{omit from|Mathematica}}
{{omit from|Maxima}}
{{omit from|ML/I}}
{{omit from|PARI/GP|No good way to access network}}
{{omit from|Retro}}
|