Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in PHP.
print defined($x) ? 'Defined' : 'Undefined', ".\n";
$x = NULL; if (is_null($x)) echo "\$x is null\n";
Generate an equivalent PHP version of this PowerShell code.
if ($null -eq $object) { ... }
$x = NULL; if (is_null($x)) echo "\$x is null\n";
Preserve the algorithm and functionality while converting the code from R to PHP.
is.null(NULL) is.null(123) is.null(NA) 123==NULL foo <- function(){} foo()
$x = NULL; if (is_null($x)) echo "\$x is null\n";
Write the same algorithm in PHP as shown in this Racket implementation.
-> null '() -> (null? null) #t -> (null? 3) #f
$x = NULL; if (is_null($x)) echo "\$x is null\n";
Port the provided COBOL code into PHP while preserving the original functionality.
identification division. program-id. null-objects. remarks. test with cobc -x -j null-objects.cob data division. working-storage section. 01 thing-not-thing usage pointer. procedure division. call "test-null" using thing-not-thing omitted returning nothing goback. end program null-objects. identification division. program-id. test-null. data division. linkage section. 01 thing-one usage pointer. 01 thing-two pic x. procedure division using thing-one optional thing-two returning omitted. if thing-one equal null then display "thing-one pointer to null" upon syserr end-if if thing-two omitted then display "no thing-two was passed" upon syserr end-if goback. end program test-null.
$x = NULL; if (is_null($x)) echo "\$x is null\n";
Please provide an equivalent version of this REXX code in PHP.
options replace format comments java crossref symbols binary robject = Rexx -- create an object for which the value is undefined say String.valueOf(robject) -- will report the text "null" if robject = null then say 'Really, it''s "null"!'
$x = NULL; if (is_null($x)) echo "\$x is null\n";
Preserve the algorithm and functionality while converting the code from Ruby to PHP.
puts "@object is nil" if @object.nil? puts "$object is nil" if $object.nil? object = 1 if false puts "object is nil" if object.nil? puts nil.class
$x = NULL; if (is_null($x)) echo "\$x is null\n";
Convert the following code from Scala to PHP, ensuring the logic remains intact.
fun main(args: Array<String>) { val i: Int = 3 println(i) val j: Int? = null println(j) println(null is Nothing?) }
$x = NULL; if (is_null($x)) echo "\$x is null\n";
Write a version of this C function in Rust with identical behavior.
#include <stdio.h> int main() { char *object = 0; if (object == NULL) { puts("object is null"); } return 0; }
fn check_number(num: &Option<u8>) { if num.is_none() { println!("Number is: None"); } else { println!("Number is: {}", num.unwrap()); } } fn main() { let mut possible_number: Option<u8> = None; check_number(&possible_number); possible_number = Some(31); check_number(&possible_number); }
Convert this C# snippet to Rust and keep its semantics consistent.
if (foo == null) Console.WriteLine("foo is null");
fn check_number(num: &Option<u8>) { if num.is_none() { println!("Number is: None"); } else { println!("Number is: {}", num.unwrap()); } } fn main() { let mut possible_number: Option<u8> = None; check_number(&possible_number); possible_number = Some(31); check_number(&possible_number); }
Change the following Java code into Rust without altering its purpose.
module NullObject { void run() { @Inject Console console; console.print($"Null value={Null}, Null.toString()={Null.toString()}"); String? s = Null; String s2 = "test"; console.print($"s={s}, s2={s2}, (s==s2)={s==s2}"); Int len = s?.size : 0; console.print($"len={len}"); if (String test ?= s) { } else { s = "a non-null value"; } s2 = s; console.print($"s={s}, s2={s2}, (s==s2)={s==s2}"); } }
fn check_number(num: &Option<u8>) { if num.is_none() { println!("Number is: None"); } else { println!("Number is: {}", num.unwrap()); } } fn main() { let mut possible_number: Option<u8> = None; check_number(&possible_number); possible_number = Some(31); check_number(&possible_number); }
Keep all operations the same but rewrite the snippet in Rust.
package main import "fmt" var ( s []int p *int f func() i interface{} m map[int]int c chan int ) func main() { fmt.Println(s == nil) fmt.Println(p == nil) fmt.Println(f == nil) fmt.Println(i == nil) fmt.Println(m == nil) fmt.Println(c == nil) }
fn check_number(num: &Option<u8>) { if num.is_none() { println!("Number is: None"); } else { println!("Number is: {}", num.unwrap()); } } fn main() { let mut possible_number: Option<u8> = None; check_number(&possible_number); possible_number = Some(31); check_number(&possible_number); }
Write the same algorithm in Python as shown in this Rust implementation.
fn check_number(num: &Option<u8>) { if num.is_none() { println!("Number is: None"); } else { println!("Number is: {}", num.unwrap()); } } fn main() { let mut possible_number: Option<u8> = None; check_number(&possible_number); possible_number = Some(31); check_number(&possible_number); }
x = None if x is None: print "x is None" else: print "x is not None"
Can you help me rewrite this code in Rust instead of C++, keeping it the same logically?
#include <iostream> #include <cstdlib> if (object == 0) { std::cout << "object is null"; }
fn check_number(num: &Option<u8>) { if num.is_none() { println!("Number is: None"); } else { println!("Number is: {}", num.unwrap()); } } fn main() { let mut possible_number: Option<u8> = None; check_number(&possible_number); possible_number = Some(31); check_number(&possible_number); }
Transform the following Rust implementation into VB, maintaining the same output and logic.
fn check_number(num: &Option<u8>) { if num.is_none() { println!("Number is: None"); } else { println!("Number is: {}", num.unwrap()); } } fn main() { let mut possible_number: Option<u8> = None; check_number(&possible_number); possible_number = Some(31); check_number(&possible_number); }
Public Sub Main() Dim c As VBA.Collection Debug.Print c Is Nothing Set c = New VBA.Collection Debug.Print Not c Is Nothing Set c = Nothing Debug.Print c Is Nothing End Sub
Produce a functionally identical C# code for the snippet given in Ada.
with Ada.Containers.Vectors; with Ada.Command_Line; use Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Sockets; use Sockets; procedure Chat_Server is package Client_Vectors is new Ada.Containers.Vectors (Element_Type => Socket_FD, Index_Type => Positive); All_Clients : Client_Vectors.Vector; procedure Write (S : String) is procedure Output (Position : Client_Vectors.Cursor) is Sock : Socket_FD := Client_Vectors.Element (Position); begin Put_Line (Sock, S); end Output; begin All_Clients.Iterate (Output'Access); end Write; task type Client_Task is entry Start (FD : Socket_FD); end Client_Task; task body Client_Task is Sock : Socket_FD; Sock_ID : Positive; Name : Unbounded_String; begin select accept Start (FD : Socket_FD) do Sock := FD; end Start; or terminate; end select; while Name = Null_Unbounded_String loop Put (Sock, "Enter Name:"); Name := To_Unbounded_String (Get_Line (Sock)); end loop; Write (To_String (Name) & " joined."); All_Clients.Append (Sock); Sock_ID := All_Clients.Find_Index (Sock); loop declare Input : String := Get_Line (Sock); begin Write (To_String (Name) & ": " & Input); end; end loop; exception when Connection_Closed => Put_Line ("Connection closed"); Shutdown (Sock, Both); All_Clients.Delete (Sock_ID); Write (To_String (Name) & " left."); end Client_Task; Accepting_Socket : Socket_FD; Incoming_Socket : Socket_FD; type Client_Access is access Client_Task; Dummy : Client_Access; begin if Argument_Count /= 1 then Raise_Exception (Constraint_Error'Identity, "Usage: " & Command_Name & " port"); end if; Socket (Accepting_Socket, PF_INET, SOCK_STREAM); Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1); Bind (Accepting_Socket, Positive'Value (Argument (1))); Listen (Accepting_Socket); loop Put_Line ("Waiting for new connection"); Accept_Socket (Accepting_Socket, Incoming_Socket); Put_Line ("New connection acknowledged"); Dummy := new Client_Task; Dummy.Start (Incoming_Socket); end loop; end Chat_Server;
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Generate a C translation of this Ada snippet without changing its computational steps.
with Ada.Containers.Vectors; with Ada.Command_Line; use Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Sockets; use Sockets; procedure Chat_Server is package Client_Vectors is new Ada.Containers.Vectors (Element_Type => Socket_FD, Index_Type => Positive); All_Clients : Client_Vectors.Vector; procedure Write (S : String) is procedure Output (Position : Client_Vectors.Cursor) is Sock : Socket_FD := Client_Vectors.Element (Position); begin Put_Line (Sock, S); end Output; begin All_Clients.Iterate (Output'Access); end Write; task type Client_Task is entry Start (FD : Socket_FD); end Client_Task; task body Client_Task is Sock : Socket_FD; Sock_ID : Positive; Name : Unbounded_String; begin select accept Start (FD : Socket_FD) do Sock := FD; end Start; or terminate; end select; while Name = Null_Unbounded_String loop Put (Sock, "Enter Name:"); Name := To_Unbounded_String (Get_Line (Sock)); end loop; Write (To_String (Name) & " joined."); All_Clients.Append (Sock); Sock_ID := All_Clients.Find_Index (Sock); loop declare Input : String := Get_Line (Sock); begin Write (To_String (Name) & ": " & Input); end; end loop; exception when Connection_Closed => Put_Line ("Connection closed"); Shutdown (Sock, Both); All_Clients.Delete (Sock_ID); Write (To_String (Name) & " left."); end Client_Task; Accepting_Socket : Socket_FD; Incoming_Socket : Socket_FD; type Client_Access is access Client_Task; Dummy : Client_Access; begin if Argument_Count /= 1 then Raise_Exception (Constraint_Error'Identity, "Usage: " & Command_Name & " port"); end if; Socket (Accepting_Socket, PF_INET, SOCK_STREAM); Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1); Bind (Accepting_Socket, Positive'Value (Argument (1))); Listen (Accepting_Socket); loop Put_Line ("Waiting for new connection"); Accept_Socket (Accepting_Socket, Incoming_Socket); Put_Line ("New connection acknowledged"); Dummy := new Client_Task; Dummy.Start (Incoming_Socket); end loop; end Chat_Server;
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Port the following code from Ada to Go with equivalent syntax and logic.
with Ada.Containers.Vectors; with Ada.Command_Line; use Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Sockets; use Sockets; procedure Chat_Server is package Client_Vectors is new Ada.Containers.Vectors (Element_Type => Socket_FD, Index_Type => Positive); All_Clients : Client_Vectors.Vector; procedure Write (S : String) is procedure Output (Position : Client_Vectors.Cursor) is Sock : Socket_FD := Client_Vectors.Element (Position); begin Put_Line (Sock, S); end Output; begin All_Clients.Iterate (Output'Access); end Write; task type Client_Task is entry Start (FD : Socket_FD); end Client_Task; task body Client_Task is Sock : Socket_FD; Sock_ID : Positive; Name : Unbounded_String; begin select accept Start (FD : Socket_FD) do Sock := FD; end Start; or terminate; end select; while Name = Null_Unbounded_String loop Put (Sock, "Enter Name:"); Name := To_Unbounded_String (Get_Line (Sock)); end loop; Write (To_String (Name) & " joined."); All_Clients.Append (Sock); Sock_ID := All_Clients.Find_Index (Sock); loop declare Input : String := Get_Line (Sock); begin Write (To_String (Name) & ": " & Input); end; end loop; exception when Connection_Closed => Put_Line ("Connection closed"); Shutdown (Sock, Both); All_Clients.Delete (Sock_ID); Write (To_String (Name) & " left."); end Client_Task; Accepting_Socket : Socket_FD; Incoming_Socket : Socket_FD; type Client_Access is access Client_Task; Dummy : Client_Access; begin if Argument_Count /= 1 then Raise_Exception (Constraint_Error'Identity, "Usage: " & Command_Name & " port"); end if; Socket (Accepting_Socket, PF_INET, SOCK_STREAM); Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1); Bind (Accepting_Socket, Positive'Value (Argument (1))); Listen (Accepting_Socket); loop Put_Line ("Waiting for new connection"); Accept_Socket (Accepting_Socket, Incoming_Socket); Put_Line ("New connection acknowledged"); Dummy := new Client_Task; Dummy.Start (Incoming_Socket); end loop; end Chat_Server;
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Preserve the algorithm and functionality while converting the code from Ada to Java.
with Ada.Containers.Vectors; with Ada.Command_Line; use Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Sockets; use Sockets; procedure Chat_Server is package Client_Vectors is new Ada.Containers.Vectors (Element_Type => Socket_FD, Index_Type => Positive); All_Clients : Client_Vectors.Vector; procedure Write (S : String) is procedure Output (Position : Client_Vectors.Cursor) is Sock : Socket_FD := Client_Vectors.Element (Position); begin Put_Line (Sock, S); end Output; begin All_Clients.Iterate (Output'Access); end Write; task type Client_Task is entry Start (FD : Socket_FD); end Client_Task; task body Client_Task is Sock : Socket_FD; Sock_ID : Positive; Name : Unbounded_String; begin select accept Start (FD : Socket_FD) do Sock := FD; end Start; or terminate; end select; while Name = Null_Unbounded_String loop Put (Sock, "Enter Name:"); Name := To_Unbounded_String (Get_Line (Sock)); end loop; Write (To_String (Name) & " joined."); All_Clients.Append (Sock); Sock_ID := All_Clients.Find_Index (Sock); loop declare Input : String := Get_Line (Sock); begin Write (To_String (Name) & ": " & Input); end; end loop; exception when Connection_Closed => Put_Line ("Connection closed"); Shutdown (Sock, Both); All_Clients.Delete (Sock_ID); Write (To_String (Name) & " left."); end Client_Task; Accepting_Socket : Socket_FD; Incoming_Socket : Socket_FD; type Client_Access is access Client_Task; Dummy : Client_Access; begin if Argument_Count /= 1 then Raise_Exception (Constraint_Error'Identity, "Usage: " & Command_Name & " port"); end if; Socket (Accepting_Socket, PF_INET, SOCK_STREAM); Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1); Bind (Accepting_Socket, Positive'Value (Argument (1))); Listen (Accepting_Socket); loop Put_Line ("Waiting for new connection"); Accept_Socket (Accepting_Socket, Incoming_Socket); Put_Line ("New connection acknowledged"); Dummy := new Client_Task; Dummy.Start (Incoming_Socket); end loop; end Chat_Server;
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Write the same algorithm in Python as shown in this Ada implementation.
with Ada.Containers.Vectors; with Ada.Command_Line; use Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Sockets; use Sockets; procedure Chat_Server is package Client_Vectors is new Ada.Containers.Vectors (Element_Type => Socket_FD, Index_Type => Positive); All_Clients : Client_Vectors.Vector; procedure Write (S : String) is procedure Output (Position : Client_Vectors.Cursor) is Sock : Socket_FD := Client_Vectors.Element (Position); begin Put_Line (Sock, S); end Output; begin All_Clients.Iterate (Output'Access); end Write; task type Client_Task is entry Start (FD : Socket_FD); end Client_Task; task body Client_Task is Sock : Socket_FD; Sock_ID : Positive; Name : Unbounded_String; begin select accept Start (FD : Socket_FD) do Sock := FD; end Start; or terminate; end select; while Name = Null_Unbounded_String loop Put (Sock, "Enter Name:"); Name := To_Unbounded_String (Get_Line (Sock)); end loop; Write (To_String (Name) & " joined."); All_Clients.Append (Sock); Sock_ID := All_Clients.Find_Index (Sock); loop declare Input : String := Get_Line (Sock); begin Write (To_String (Name) & ": " & Input); end; end loop; exception when Connection_Closed => Put_Line ("Connection closed"); Shutdown (Sock, Both); All_Clients.Delete (Sock_ID); Write (To_String (Name) & " left."); end Client_Task; Accepting_Socket : Socket_FD; Incoming_Socket : Socket_FD; type Client_Access is access Client_Task; Dummy : Client_Access; begin if Argument_Count /= 1 then Raise_Exception (Constraint_Error'Identity, "Usage: " & Command_Name & " port"); end if; Socket (Accepting_Socket, PF_INET, SOCK_STREAM); Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1); Bind (Accepting_Socket, Positive'Value (Argument (1))); Listen (Accepting_Socket); loop Put_Line ("Waiting for new connection"); Accept_Socket (Accepting_Socket, Incoming_Socket); Put_Line ("New connection acknowledged"); Dummy := new Client_Task; Dummy.Start (Incoming_Socket); end loop; end Chat_Server;
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Write a version of this Ada function in VB with identical behavior.
with Ada.Containers.Vectors; with Ada.Command_Line; use Ada.Command_Line; with Ada.Exceptions; use Ada.Exceptions; with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Sockets; use Sockets; procedure Chat_Server is package Client_Vectors is new Ada.Containers.Vectors (Element_Type => Socket_FD, Index_Type => Positive); All_Clients : Client_Vectors.Vector; procedure Write (S : String) is procedure Output (Position : Client_Vectors.Cursor) is Sock : Socket_FD := Client_Vectors.Element (Position); begin Put_Line (Sock, S); end Output; begin All_Clients.Iterate (Output'Access); end Write; task type Client_Task is entry Start (FD : Socket_FD); end Client_Task; task body Client_Task is Sock : Socket_FD; Sock_ID : Positive; Name : Unbounded_String; begin select accept Start (FD : Socket_FD) do Sock := FD; end Start; or terminate; end select; while Name = Null_Unbounded_String loop Put (Sock, "Enter Name:"); Name := To_Unbounded_String (Get_Line (Sock)); end loop; Write (To_String (Name) & " joined."); All_Clients.Append (Sock); Sock_ID := All_Clients.Find_Index (Sock); loop declare Input : String := Get_Line (Sock); begin Write (To_String (Name) & ": " & Input); end; end loop; exception when Connection_Closed => Put_Line ("Connection closed"); Shutdown (Sock, Both); All_Clients.Delete (Sock_ID); Write (To_String (Name) & " left."); end Client_Task; Accepting_Socket : Socket_FD; Incoming_Socket : Socket_FD; type Client_Access is access Client_Task; Dummy : Client_Access; begin if Argument_Count /= 1 then Raise_Exception (Constraint_Error'Identity, "Usage: " & Command_Name & " port"); end if; Socket (Accepting_Socket, PF_INET, SOCK_STREAM); Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1); Bind (Accepting_Socket, Positive'Value (Argument (1))); Listen (Accepting_Socket); loop Put_Line ("Waiting for new connection"); Accept_Socket (Accepting_Socket, Incoming_Socket); Put_Line ("New connection acknowledged"); Dummy := new Client_Task; Dummy.Start (Incoming_Socket); end loop; end Chat_Server;
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Produce a language-to-language conversion: from D to C, same semantics.
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(); } }
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Preserve the algorithm and functionality while converting the code from D to C#.
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(); } }
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Change the following D code into Java without altering its purpose.
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(); } }
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Ensure the translated Python code behaves exactly like the original D snippet.
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(); } }
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Maintain the same structure and functionality when rewriting this code in VB.
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(); } }
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Convert this D snippet to Go and keep its semantics consistent.
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(); } }
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Change the following Erlang code into C without altering its purpose.
-module(chat). -export([start/0, start/1]). -record(client, {name=none, socket=none}). start() -> start(8080). start(Port) -> register(server, spawn(fun() -> server() end)), {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]), accept(LSocket). server() -> server([]). server(Clients) -> receive {join, Client=#client{name = Name, socket = Socket}} -> self() ! {say, Socket, "has joined." ++ [10, 13]}, server(Clients ++ [Client]); {leave, Socket} -> {value, #client{name = Name}, List} = lists:keytake(Socket, 3, Clients), self() ! {say, none, Message = "has left."}, server(List); {say, Socket, Data} -> {value, #client{name = From}, List} = lists:keytake(Socket, 3, Clients), Message = From ++ " : " ++ Data, lists:map(fun(#client{socket = S}) -> gen_tcp:send(S, Message) end, List) end, server(Clients). accept(LSocket) -> {ok, Socket} = gen_tcp:accept(LSocket), spawn(fun() -> connecting(Socket) end), accept(LSocket). connecting(Socket) -> gen_tcp:send(Socket, "What is your name? "), case listen(Socket) of {ok, N} -> Name = binary_to_list(N), server ! {join, #client{name = lists:sublist(Name, 1, length(Name) - 2), socket = Socket} }, client(Socket); _ -> ok end. client(Socket) -> case listen(Socket) of {ok, Data} -> server ! {say, Socket, binary_to_list(Data)}, client(Socket); _ -> server ! {leave, Socket} end. listen(Socket) -> case gen_tcp:recv(Socket, 0) of Response -> Response end.
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Keep all operations the same but rewrite the snippet in C#.
-module(chat). -export([start/0, start/1]). -record(client, {name=none, socket=none}). start() -> start(8080). start(Port) -> register(server, spawn(fun() -> server() end)), {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]), accept(LSocket). server() -> server([]). server(Clients) -> receive {join, Client=#client{name = Name, socket = Socket}} -> self() ! {say, Socket, "has joined." ++ [10, 13]}, server(Clients ++ [Client]); {leave, Socket} -> {value, #client{name = Name}, List} = lists:keytake(Socket, 3, Clients), self() ! {say, none, Message = "has left."}, server(List); {say, Socket, Data} -> {value, #client{name = From}, List} = lists:keytake(Socket, 3, Clients), Message = From ++ " : " ++ Data, lists:map(fun(#client{socket = S}) -> gen_tcp:send(S, Message) end, List) end, server(Clients). accept(LSocket) -> {ok, Socket} = gen_tcp:accept(LSocket), spawn(fun() -> connecting(Socket) end), accept(LSocket). connecting(Socket) -> gen_tcp:send(Socket, "What is your name? "), case listen(Socket) of {ok, N} -> Name = binary_to_list(N), server ! {join, #client{name = lists:sublist(Name, 1, length(Name) - 2), socket = Socket} }, client(Socket); _ -> ok end. client(Socket) -> case listen(Socket) of {ok, Data} -> server ! {say, Socket, binary_to_list(Data)}, client(Socket); _ -> server ! {leave, Socket} end. listen(Socket) -> case gen_tcp:recv(Socket, 0) of Response -> Response end.
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Maintain the same structure and functionality when rewriting this code in Java.
-module(chat). -export([start/0, start/1]). -record(client, {name=none, socket=none}). start() -> start(8080). start(Port) -> register(server, spawn(fun() -> server() end)), {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]), accept(LSocket). server() -> server([]). server(Clients) -> receive {join, Client=#client{name = Name, socket = Socket}} -> self() ! {say, Socket, "has joined." ++ [10, 13]}, server(Clients ++ [Client]); {leave, Socket} -> {value, #client{name = Name}, List} = lists:keytake(Socket, 3, Clients), self() ! {say, none, Message = "has left."}, server(List); {say, Socket, Data} -> {value, #client{name = From}, List} = lists:keytake(Socket, 3, Clients), Message = From ++ " : " ++ Data, lists:map(fun(#client{socket = S}) -> gen_tcp:send(S, Message) end, List) end, server(Clients). accept(LSocket) -> {ok, Socket} = gen_tcp:accept(LSocket), spawn(fun() -> connecting(Socket) end), accept(LSocket). connecting(Socket) -> gen_tcp:send(Socket, "What is your name? "), case listen(Socket) of {ok, N} -> Name = binary_to_list(N), server ! {join, #client{name = lists:sublist(Name, 1, length(Name) - 2), socket = Socket} }, client(Socket); _ -> ok end. client(Socket) -> case listen(Socket) of {ok, Data} -> server ! {say, Socket, binary_to_list(Data)}, client(Socket); _ -> server ! {leave, Socket} end. listen(Socket) -> case gen_tcp:recv(Socket, 0) of Response -> Response end.
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Produce a language-to-language conversion: from Erlang to Python, same semantics.
-module(chat). -export([start/0, start/1]). -record(client, {name=none, socket=none}). start() -> start(8080). start(Port) -> register(server, spawn(fun() -> server() end)), {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]), accept(LSocket). server() -> server([]). server(Clients) -> receive {join, Client=#client{name = Name, socket = Socket}} -> self() ! {say, Socket, "has joined." ++ [10, 13]}, server(Clients ++ [Client]); {leave, Socket} -> {value, #client{name = Name}, List} = lists:keytake(Socket, 3, Clients), self() ! {say, none, Message = "has left."}, server(List); {say, Socket, Data} -> {value, #client{name = From}, List} = lists:keytake(Socket, 3, Clients), Message = From ++ " : " ++ Data, lists:map(fun(#client{socket = S}) -> gen_tcp:send(S, Message) end, List) end, server(Clients). accept(LSocket) -> {ok, Socket} = gen_tcp:accept(LSocket), spawn(fun() -> connecting(Socket) end), accept(LSocket). connecting(Socket) -> gen_tcp:send(Socket, "What is your name? "), case listen(Socket) of {ok, N} -> Name = binary_to_list(N), server ! {join, #client{name = lists:sublist(Name, 1, length(Name) - 2), socket = Socket} }, client(Socket); _ -> ok end. client(Socket) -> case listen(Socket) of {ok, Data} -> server ! {say, Socket, binary_to_list(Data)}, client(Socket); _ -> server ! {leave, Socket} end. listen(Socket) -> case gen_tcp:recv(Socket, 0) of Response -> Response end.
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Please provide an equivalent version of this Erlang code in VB.
-module(chat). -export([start/0, start/1]). -record(client, {name=none, socket=none}). start() -> start(8080). start(Port) -> register(server, spawn(fun() -> server() end)), {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]), accept(LSocket). server() -> server([]). server(Clients) -> receive {join, Client=#client{name = Name, socket = Socket}} -> self() ! {say, Socket, "has joined." ++ [10, 13]}, server(Clients ++ [Client]); {leave, Socket} -> {value, #client{name = Name}, List} = lists:keytake(Socket, 3, Clients), self() ! {say, none, Message = "has left."}, server(List); {say, Socket, Data} -> {value, #client{name = From}, List} = lists:keytake(Socket, 3, Clients), Message = From ++ " : " ++ Data, lists:map(fun(#client{socket = S}) -> gen_tcp:send(S, Message) end, List) end, server(Clients). accept(LSocket) -> {ok, Socket} = gen_tcp:accept(LSocket), spawn(fun() -> connecting(Socket) end), accept(LSocket). connecting(Socket) -> gen_tcp:send(Socket, "What is your name? "), case listen(Socket) of {ok, N} -> Name = binary_to_list(N), server ! {join, #client{name = lists:sublist(Name, 1, length(Name) - 2), socket = Socket} }, client(Socket); _ -> ok end. client(Socket) -> case listen(Socket) of {ok, Data} -> server ! {say, Socket, binary_to_list(Data)}, client(Socket); _ -> server ! {leave, Socket} end. listen(Socket) -> case gen_tcp:recv(Socket, 0) of Response -> Response end.
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Convert the following code from Erlang to Go, ensuring the logic remains intact.
-module(chat). -export([start/0, start/1]). -record(client, {name=none, socket=none}). start() -> start(8080). start(Port) -> register(server, spawn(fun() -> server() end)), {ok, LSocket} = gen_tcp:listen(Port, [binary, {packet, 0}, {active, false}, {reuseaddr, true}]), accept(LSocket). server() -> server([]). server(Clients) -> receive {join, Client=#client{name = Name, socket = Socket}} -> self() ! {say, Socket, "has joined." ++ [10, 13]}, server(Clients ++ [Client]); {leave, Socket} -> {value, #client{name = Name}, List} = lists:keytake(Socket, 3, Clients), self() ! {say, none, Message = "has left."}, server(List); {say, Socket, Data} -> {value, #client{name = From}, List} = lists:keytake(Socket, 3, Clients), Message = From ++ " : " ++ Data, lists:map(fun(#client{socket = S}) -> gen_tcp:send(S, Message) end, List) end, server(Clients). accept(LSocket) -> {ok, Socket} = gen_tcp:accept(LSocket), spawn(fun() -> connecting(Socket) end), accept(LSocket). connecting(Socket) -> gen_tcp:send(Socket, "What is your name? "), case listen(Socket) of {ok, N} -> Name = binary_to_list(N), server ! {join, #client{name = lists:sublist(Name, 1, length(Name) - 2), socket = Socket} }, client(Socket); _ -> ok end. client(Socket) -> case listen(Socket) of {ok, Data} -> server ! {say, Socket, binary_to_list(Data)}, client(Socket); _ -> server ! {leave, Socket} end. listen(Socket) -> case gen_tcp:recv(Socket, 0) of Response -> Response end.
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Port the provided Groovy code into C while preserving the original functionality.
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>() ChatServer(int port) { this.port = port } @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = new ServerSocket(port) while (true) { Socket socket = serverSocket.accept() new Thread(new Client(socket)).start() } } catch (Exception e) { e.printStackTrace() } } private synchronized boolean registerClient(Client client) { for (Client other : clientList) { if (other.clientName.equalsIgnoreCase(client.clientName)) { return false } } clientList.add(client) return true } private void deRegisterClient(Client client) { boolean wasRegistered synchronized (this) { wasRegistered = clientList.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder() sb.append(clientList.size()).append(" user(s) online: ") def it = clientList.iterator() if (it.hasNext()) { sb.append(it.next().clientName) } while (it.hasNext()) { sb.append(", ") sb.append(it.next().clientName) } return sb.toString() } private void broadcast(Client fromClient, String msg) { List<Client> clients synchronized (this) { clients = new ArrayList<>(this.clientList) } for (Client client : clients) { if (client == fromClient) { continue } try { client.write(msg + "\r\n") } catch (Exception ignored) { } } } class Client implements Runnable { private Socket socket = null private Writer output = null private String clientName = null Client(Socket socket) { this.socket = socket } @Override void run() { try { socket.setSendBufferSize(16384) socket.setTcpNoDelay(true) BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())) output = new OutputStreamWriter(socket.getOutputStream()) write("Please enter your name: ") String line while (null != (line = input.readLine())) { if (null == clientName) { line = line.trim() if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(getOnlineListCSV() + "\r\n") broadcast(this, "+++ " + clientName + " arrived +++") continue } if (line.equalsIgnoreCase("/quit")) { return } broadcast(this, clientName + "> " + line) } } catch (Exception ignored) { } finally { deRegisterClient(this) output = null try { socket.close() } catch (Exception ignored) { } socket = null } } void write(String msg) { output.write(msg) output.flush() } @Override boolean equals(client) { return (null != client) && (client instanceof Client) && (null != clientName) && clientName == client.clientName } @Override int hashCode() { int result result = (socket != null ? socket.hashCode() : 0) result = 31 * result + (output != null ? output.hashCode() : 0) result = 31 * result + (clientName != null ? clientName.hashCode() : 0) return result } } static void main(String[] args) { int port = 4004 if (args.length > 0) { port = Integer.parseInt(args[0]) } new ChatServer(port).run() } }
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Convert this Groovy block to C#, preserving its control flow and logic.
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>() ChatServer(int port) { this.port = port } @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = new ServerSocket(port) while (true) { Socket socket = serverSocket.accept() new Thread(new Client(socket)).start() } } catch (Exception e) { e.printStackTrace() } } private synchronized boolean registerClient(Client client) { for (Client other : clientList) { if (other.clientName.equalsIgnoreCase(client.clientName)) { return false } } clientList.add(client) return true } private void deRegisterClient(Client client) { boolean wasRegistered synchronized (this) { wasRegistered = clientList.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder() sb.append(clientList.size()).append(" user(s) online: ") def it = clientList.iterator() if (it.hasNext()) { sb.append(it.next().clientName) } while (it.hasNext()) { sb.append(", ") sb.append(it.next().clientName) } return sb.toString() } private void broadcast(Client fromClient, String msg) { List<Client> clients synchronized (this) { clients = new ArrayList<>(this.clientList) } for (Client client : clients) { if (client == fromClient) { continue } try { client.write(msg + "\r\n") } catch (Exception ignored) { } } } class Client implements Runnable { private Socket socket = null private Writer output = null private String clientName = null Client(Socket socket) { this.socket = socket } @Override void run() { try { socket.setSendBufferSize(16384) socket.setTcpNoDelay(true) BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())) output = new OutputStreamWriter(socket.getOutputStream()) write("Please enter your name: ") String line while (null != (line = input.readLine())) { if (null == clientName) { line = line.trim() if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(getOnlineListCSV() + "\r\n") broadcast(this, "+++ " + clientName + " arrived +++") continue } if (line.equalsIgnoreCase("/quit")) { return } broadcast(this, clientName + "> " + line) } } catch (Exception ignored) { } finally { deRegisterClient(this) output = null try { socket.close() } catch (Exception ignored) { } socket = null } } void write(String msg) { output.write(msg) output.flush() } @Override boolean equals(client) { return (null != client) && (client instanceof Client) && (null != clientName) && clientName == client.clientName } @Override int hashCode() { int result result = (socket != null ? socket.hashCode() : 0) result = 31 * result + (output != null ? output.hashCode() : 0) result = 31 * result + (clientName != null ? clientName.hashCode() : 0) return result } } static void main(String[] args) { int port = 4004 if (args.length > 0) { port = Integer.parseInt(args[0]) } new ChatServer(port).run() } }
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Ensure the translated Java code behaves exactly like the original Groovy snippet.
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>() ChatServer(int port) { this.port = port } @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = new ServerSocket(port) while (true) { Socket socket = serverSocket.accept() new Thread(new Client(socket)).start() } } catch (Exception e) { e.printStackTrace() } } private synchronized boolean registerClient(Client client) { for (Client other : clientList) { if (other.clientName.equalsIgnoreCase(client.clientName)) { return false } } clientList.add(client) return true } private void deRegisterClient(Client client) { boolean wasRegistered synchronized (this) { wasRegistered = clientList.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder() sb.append(clientList.size()).append(" user(s) online: ") def it = clientList.iterator() if (it.hasNext()) { sb.append(it.next().clientName) } while (it.hasNext()) { sb.append(", ") sb.append(it.next().clientName) } return sb.toString() } private void broadcast(Client fromClient, String msg) { List<Client> clients synchronized (this) { clients = new ArrayList<>(this.clientList) } for (Client client : clients) { if (client == fromClient) { continue } try { client.write(msg + "\r\n") } catch (Exception ignored) { } } } class Client implements Runnable { private Socket socket = null private Writer output = null private String clientName = null Client(Socket socket) { this.socket = socket } @Override void run() { try { socket.setSendBufferSize(16384) socket.setTcpNoDelay(true) BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())) output = new OutputStreamWriter(socket.getOutputStream()) write("Please enter your name: ") String line while (null != (line = input.readLine())) { if (null == clientName) { line = line.trim() if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(getOnlineListCSV() + "\r\n") broadcast(this, "+++ " + clientName + " arrived +++") continue } if (line.equalsIgnoreCase("/quit")) { return } broadcast(this, clientName + "> " + line) } } catch (Exception ignored) { } finally { deRegisterClient(this) output = null try { socket.close() } catch (Exception ignored) { } socket = null } } void write(String msg) { output.write(msg) output.flush() } @Override boolean equals(client) { return (null != client) && (client instanceof Client) && (null != clientName) && clientName == client.clientName } @Override int hashCode() { int result result = (socket != null ? socket.hashCode() : 0) result = 31 * result + (output != null ? output.hashCode() : 0) result = 31 * result + (clientName != null ? clientName.hashCode() : 0) return result } } static void main(String[] args) { int port = 4004 if (args.length > 0) { port = Integer.parseInt(args[0]) } new ChatServer(port).run() } }
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Convert this Groovy block to Python, preserving its control flow and logic.
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>() ChatServer(int port) { this.port = port } @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = new ServerSocket(port) while (true) { Socket socket = serverSocket.accept() new Thread(new Client(socket)).start() } } catch (Exception e) { e.printStackTrace() } } private synchronized boolean registerClient(Client client) { for (Client other : clientList) { if (other.clientName.equalsIgnoreCase(client.clientName)) { return false } } clientList.add(client) return true } private void deRegisterClient(Client client) { boolean wasRegistered synchronized (this) { wasRegistered = clientList.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder() sb.append(clientList.size()).append(" user(s) online: ") def it = clientList.iterator() if (it.hasNext()) { sb.append(it.next().clientName) } while (it.hasNext()) { sb.append(", ") sb.append(it.next().clientName) } return sb.toString() } private void broadcast(Client fromClient, String msg) { List<Client> clients synchronized (this) { clients = new ArrayList<>(this.clientList) } for (Client client : clients) { if (client == fromClient) { continue } try { client.write(msg + "\r\n") } catch (Exception ignored) { } } } class Client implements Runnable { private Socket socket = null private Writer output = null private String clientName = null Client(Socket socket) { this.socket = socket } @Override void run() { try { socket.setSendBufferSize(16384) socket.setTcpNoDelay(true) BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())) output = new OutputStreamWriter(socket.getOutputStream()) write("Please enter your name: ") String line while (null != (line = input.readLine())) { if (null == clientName) { line = line.trim() if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(getOnlineListCSV() + "\r\n") broadcast(this, "+++ " + clientName + " arrived +++") continue } if (line.equalsIgnoreCase("/quit")) { return } broadcast(this, clientName + "> " + line) } } catch (Exception ignored) { } finally { deRegisterClient(this) output = null try { socket.close() } catch (Exception ignored) { } socket = null } } void write(String msg) { output.write(msg) output.flush() } @Override boolean equals(client) { return (null != client) && (client instanceof Client) && (null != clientName) && clientName == client.clientName } @Override int hashCode() { int result result = (socket != null ? socket.hashCode() : 0) result = 31 * result + (output != null ? output.hashCode() : 0) result = 31 * result + (clientName != null ? clientName.hashCode() : 0) return result } } static void main(String[] args) { int port = 4004 if (args.length > 0) { port = Integer.parseInt(args[0]) } new ChatServer(port).run() } }
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Please provide an equivalent version of this Groovy code in VB.
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>() ChatServer(int port) { this.port = port } @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = new ServerSocket(port) while (true) { Socket socket = serverSocket.accept() new Thread(new Client(socket)).start() } } catch (Exception e) { e.printStackTrace() } } private synchronized boolean registerClient(Client client) { for (Client other : clientList) { if (other.clientName.equalsIgnoreCase(client.clientName)) { return false } } clientList.add(client) return true } private void deRegisterClient(Client client) { boolean wasRegistered synchronized (this) { wasRegistered = clientList.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder() sb.append(clientList.size()).append(" user(s) online: ") def it = clientList.iterator() if (it.hasNext()) { sb.append(it.next().clientName) } while (it.hasNext()) { sb.append(", ") sb.append(it.next().clientName) } return sb.toString() } private void broadcast(Client fromClient, String msg) { List<Client> clients synchronized (this) { clients = new ArrayList<>(this.clientList) } for (Client client : clients) { if (client == fromClient) { continue } try { client.write(msg + "\r\n") } catch (Exception ignored) { } } } class Client implements Runnable { private Socket socket = null private Writer output = null private String clientName = null Client(Socket socket) { this.socket = socket } @Override void run() { try { socket.setSendBufferSize(16384) socket.setTcpNoDelay(true) BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())) output = new OutputStreamWriter(socket.getOutputStream()) write("Please enter your name: ") String line while (null != (line = input.readLine())) { if (null == clientName) { line = line.trim() if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(getOnlineListCSV() + "\r\n") broadcast(this, "+++ " + clientName + " arrived +++") continue } if (line.equalsIgnoreCase("/quit")) { return } broadcast(this, clientName + "> " + line) } } catch (Exception ignored) { } finally { deRegisterClient(this) output = null try { socket.close() } catch (Exception ignored) { } socket = null } } void write(String msg) { output.write(msg) output.flush() } @Override boolean equals(client) { return (null != client) && (client instanceof Client) && (null != clientName) && clientName == client.clientName } @Override int hashCode() { int result result = (socket != null ? socket.hashCode() : 0) result = 31 * result + (output != null ? output.hashCode() : 0) result = 31 * result + (clientName != null ? clientName.hashCode() : 0) return result } } static void main(String[] args) { int port = 4004 if (args.length > 0) { port = Integer.parseInt(args[0]) } new ChatServer(port).run() } }
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Produce a language-to-language conversion: from Groovy to Go, same semantics.
class ChatServer implements Runnable { private int port = 0 private List<Client> clientList = new ArrayList<>() ChatServer(int port) { this.port = port } @SuppressWarnings("GroovyInfiniteLoopStatement") @Override void run() { try { ServerSocket serverSocket = new ServerSocket(port) while (true) { Socket socket = serverSocket.accept() new Thread(new Client(socket)).start() } } catch (Exception e) { e.printStackTrace() } } private synchronized boolean registerClient(Client client) { for (Client other : clientList) { if (other.clientName.equalsIgnoreCase(client.clientName)) { return false } } clientList.add(client) return true } private void deRegisterClient(Client client) { boolean wasRegistered synchronized (this) { wasRegistered = clientList.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder() sb.append(clientList.size()).append(" user(s) online: ") def it = clientList.iterator() if (it.hasNext()) { sb.append(it.next().clientName) } while (it.hasNext()) { sb.append(", ") sb.append(it.next().clientName) } return sb.toString() } private void broadcast(Client fromClient, String msg) { List<Client> clients synchronized (this) { clients = new ArrayList<>(this.clientList) } for (Client client : clients) { if (client == fromClient) { continue } try { client.write(msg + "\r\n") } catch (Exception ignored) { } } } class Client implements Runnable { private Socket socket = null private Writer output = null private String clientName = null Client(Socket socket) { this.socket = socket } @Override void run() { try { socket.setSendBufferSize(16384) socket.setTcpNoDelay(true) BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())) output = new OutputStreamWriter(socket.getOutputStream()) write("Please enter your name: ") String line while (null != (line = input.readLine())) { if (null == clientName) { line = line.trim() if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(getOnlineListCSV() + "\r\n") broadcast(this, "+++ " + clientName + " arrived +++") continue } if (line.equalsIgnoreCase("/quit")) { return } broadcast(this, clientName + "> " + line) } } catch (Exception ignored) { } finally { deRegisterClient(this) output = null try { socket.close() } catch (Exception ignored) { } socket = null } } void write(String msg) { output.write(msg) output.flush() } @Override boolean equals(client) { return (null != client) && (client instanceof Client) && (null != clientName) && clientName == client.clientName } @Override int hashCode() { int result result = (socket != null ? socket.hashCode() : 0) result = 31 * result + (output != null ? output.hashCode() : 0) result = 31 * result + (clientName != null ? clientName.hashCode() : 0) return result } } static void main(String[] args) { int port = 4004 if (args.length > 0) { port = Integer.parseInt(args[0]) } new ChatServer(port).run() } }
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Convert this Haskell block to C, preserving its control flow and logic.
import Network import System.IO import Control.Concurrent import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import qualified Data.Map as M import Data.Map (Map) import Control.Monad.Reader import Control.Monad.Error import Control.Exception import Data.Monoid import Control.Applicative type ServerApp = ReaderT ThreadData IO data Speaker = Server | Client Text data ThreadData = ThreadData { threadHandle :: Handle , userTableMV :: MVar (Map Text Handle)} echoLocal = liftIO . T.putStrLn echoRemote = echoMessage . (">> "<>) echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg getRemoteLine = viewHandle >>= liftIO . T.hGetLine putMVarT = (liftIO.) . putMVar takeMVarT = liftIO . takeMVar readMVarT = liftIO . readMVar modifyUserTable fn = viewUsers >>= \mv -> liftIO $ modifyMVar_ mv (return . fn) viewHandle = threadHandle <$> ask viewUsers = userTableMV <$> ask userChat :: ServerApp () userChat = do name <- addUser echoLocal name h <- viewHandle (flip catchError) (\_ -> removeUser name) $ do echoLocal $ "Accepted " <> name forever $ getRemoteLine >>= broadcast (Client name) removeUser :: Text -> ServerApp () removeUser name = do echoLocal $ "Exception with " <> name <> ", removing from userTable" broadcast Server $ name <> " has left the server" modifyUserTable (M.delete name) addUser :: ServerApp Text addUser = do h <- viewHandle usersMV <- viewUsers echoRemote "Enter username" name <- T.filter (/='\r') <$> getRemoteLine userTable <- takeMVarT usersMV if name `M.member` userTable then do echoRemote "Username already exists!" putMVarT usersMV userTable addUser else do putMVarT usersMV (M.insert name h userTable) broadcast Server $ name <> " has joined the server" echoRemote "Welcome to the server!\n>> Other users:" readMVarT usersMV >>= mapM_ (echoRemote . ("*" <>) . fst) . filter ((/=name). fst) . M.toList return name broadcast :: Speaker -> Text -> ServerApp () broadcast user msg = viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList where f h = liftIO $ T.hPutStrLn h $ nm <> msg (fn, nm) = case user of Server -> (id, ">> ") Client t -> (filter ((/=t) . fst), t <> "> ") clientLoop socket users = do (h, _, _) <- accept socket hSetBuffering h LineBuffering forkIO $ runReaderT userChat (ThreadData h users) clientLoop socket users main = do server <- listenOn $ PortNumber 5002 T.putStrLn "Server started" newMVar (M.empty) >>= clientLoop server
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Transform the following Haskell implementation into C#, maintaining the same output and logic.
import Network import System.IO import Control.Concurrent import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import qualified Data.Map as M import Data.Map (Map) import Control.Monad.Reader import Control.Monad.Error import Control.Exception import Data.Monoid import Control.Applicative type ServerApp = ReaderT ThreadData IO data Speaker = Server | Client Text data ThreadData = ThreadData { threadHandle :: Handle , userTableMV :: MVar (Map Text Handle)} echoLocal = liftIO . T.putStrLn echoRemote = echoMessage . (">> "<>) echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg getRemoteLine = viewHandle >>= liftIO . T.hGetLine putMVarT = (liftIO.) . putMVar takeMVarT = liftIO . takeMVar readMVarT = liftIO . readMVar modifyUserTable fn = viewUsers >>= \mv -> liftIO $ modifyMVar_ mv (return . fn) viewHandle = threadHandle <$> ask viewUsers = userTableMV <$> ask userChat :: ServerApp () userChat = do name <- addUser echoLocal name h <- viewHandle (flip catchError) (\_ -> removeUser name) $ do echoLocal $ "Accepted " <> name forever $ getRemoteLine >>= broadcast (Client name) removeUser :: Text -> ServerApp () removeUser name = do echoLocal $ "Exception with " <> name <> ", removing from userTable" broadcast Server $ name <> " has left the server" modifyUserTable (M.delete name) addUser :: ServerApp Text addUser = do h <- viewHandle usersMV <- viewUsers echoRemote "Enter username" name <- T.filter (/='\r') <$> getRemoteLine userTable <- takeMVarT usersMV if name `M.member` userTable then do echoRemote "Username already exists!" putMVarT usersMV userTable addUser else do putMVarT usersMV (M.insert name h userTable) broadcast Server $ name <> " has joined the server" echoRemote "Welcome to the server!\n>> Other users:" readMVarT usersMV >>= mapM_ (echoRemote . ("*" <>) . fst) . filter ((/=name). fst) . M.toList return name broadcast :: Speaker -> Text -> ServerApp () broadcast user msg = viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList where f h = liftIO $ T.hPutStrLn h $ nm <> msg (fn, nm) = case user of Server -> (id, ">> ") Client t -> (filter ((/=t) . fst), t <> "> ") clientLoop socket users = do (h, _, _) <- accept socket hSetBuffering h LineBuffering forkIO $ runReaderT userChat (ThreadData h users) clientLoop socket users main = do server <- listenOn $ PortNumber 5002 T.putStrLn "Server started" newMVar (M.empty) >>= clientLoop server
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Convert this Haskell block to Java, preserving its control flow and logic.
import Network import System.IO import Control.Concurrent import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import qualified Data.Map as M import Data.Map (Map) import Control.Monad.Reader import Control.Monad.Error import Control.Exception import Data.Monoid import Control.Applicative type ServerApp = ReaderT ThreadData IO data Speaker = Server | Client Text data ThreadData = ThreadData { threadHandle :: Handle , userTableMV :: MVar (Map Text Handle)} echoLocal = liftIO . T.putStrLn echoRemote = echoMessage . (">> "<>) echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg getRemoteLine = viewHandle >>= liftIO . T.hGetLine putMVarT = (liftIO.) . putMVar takeMVarT = liftIO . takeMVar readMVarT = liftIO . readMVar modifyUserTable fn = viewUsers >>= \mv -> liftIO $ modifyMVar_ mv (return . fn) viewHandle = threadHandle <$> ask viewUsers = userTableMV <$> ask userChat :: ServerApp () userChat = do name <- addUser echoLocal name h <- viewHandle (flip catchError) (\_ -> removeUser name) $ do echoLocal $ "Accepted " <> name forever $ getRemoteLine >>= broadcast (Client name) removeUser :: Text -> ServerApp () removeUser name = do echoLocal $ "Exception with " <> name <> ", removing from userTable" broadcast Server $ name <> " has left the server" modifyUserTable (M.delete name) addUser :: ServerApp Text addUser = do h <- viewHandle usersMV <- viewUsers echoRemote "Enter username" name <- T.filter (/='\r') <$> getRemoteLine userTable <- takeMVarT usersMV if name `M.member` userTable then do echoRemote "Username already exists!" putMVarT usersMV userTable addUser else do putMVarT usersMV (M.insert name h userTable) broadcast Server $ name <> " has joined the server" echoRemote "Welcome to the server!\n>> Other users:" readMVarT usersMV >>= mapM_ (echoRemote . ("*" <>) . fst) . filter ((/=name). fst) . M.toList return name broadcast :: Speaker -> Text -> ServerApp () broadcast user msg = viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList where f h = liftIO $ T.hPutStrLn h $ nm <> msg (fn, nm) = case user of Server -> (id, ">> ") Client t -> (filter ((/=t) . fst), t <> "> ") clientLoop socket users = do (h, _, _) <- accept socket hSetBuffering h LineBuffering forkIO $ runReaderT userChat (ThreadData h users) clientLoop socket users main = do server <- listenOn $ PortNumber 5002 T.putStrLn "Server started" newMVar (M.empty) >>= clientLoop server
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Port the provided Haskell code into Python while preserving the original functionality.
import Network import System.IO import Control.Concurrent import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import qualified Data.Map as M import Data.Map (Map) import Control.Monad.Reader import Control.Monad.Error import Control.Exception import Data.Monoid import Control.Applicative type ServerApp = ReaderT ThreadData IO data Speaker = Server | Client Text data ThreadData = ThreadData { threadHandle :: Handle , userTableMV :: MVar (Map Text Handle)} echoLocal = liftIO . T.putStrLn echoRemote = echoMessage . (">> "<>) echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg getRemoteLine = viewHandle >>= liftIO . T.hGetLine putMVarT = (liftIO.) . putMVar takeMVarT = liftIO . takeMVar readMVarT = liftIO . readMVar modifyUserTable fn = viewUsers >>= \mv -> liftIO $ modifyMVar_ mv (return . fn) viewHandle = threadHandle <$> ask viewUsers = userTableMV <$> ask userChat :: ServerApp () userChat = do name <- addUser echoLocal name h <- viewHandle (flip catchError) (\_ -> removeUser name) $ do echoLocal $ "Accepted " <> name forever $ getRemoteLine >>= broadcast (Client name) removeUser :: Text -> ServerApp () removeUser name = do echoLocal $ "Exception with " <> name <> ", removing from userTable" broadcast Server $ name <> " has left the server" modifyUserTable (M.delete name) addUser :: ServerApp Text addUser = do h <- viewHandle usersMV <- viewUsers echoRemote "Enter username" name <- T.filter (/='\r') <$> getRemoteLine userTable <- takeMVarT usersMV if name `M.member` userTable then do echoRemote "Username already exists!" putMVarT usersMV userTable addUser else do putMVarT usersMV (M.insert name h userTable) broadcast Server $ name <> " has joined the server" echoRemote "Welcome to the server!\n>> Other users:" readMVarT usersMV >>= mapM_ (echoRemote . ("*" <>) . fst) . filter ((/=name). fst) . M.toList return name broadcast :: Speaker -> Text -> ServerApp () broadcast user msg = viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList where f h = liftIO $ T.hPutStrLn h $ nm <> msg (fn, nm) = case user of Server -> (id, ">> ") Client t -> (filter ((/=t) . fst), t <> "> ") clientLoop socket users = do (h, _, _) <- accept socket hSetBuffering h LineBuffering forkIO $ runReaderT userChat (ThreadData h users) clientLoop socket users main = do server <- listenOn $ PortNumber 5002 T.putStrLn "Server started" newMVar (M.empty) >>= clientLoop server
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Port the following code from Haskell to VB with equivalent syntax and logic.
import Network import System.IO import Control.Concurrent import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import qualified Data.Map as M import Data.Map (Map) import Control.Monad.Reader import Control.Monad.Error import Control.Exception import Data.Monoid import Control.Applicative type ServerApp = ReaderT ThreadData IO data Speaker = Server | Client Text data ThreadData = ThreadData { threadHandle :: Handle , userTableMV :: MVar (Map Text Handle)} echoLocal = liftIO . T.putStrLn echoRemote = echoMessage . (">> "<>) echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg getRemoteLine = viewHandle >>= liftIO . T.hGetLine putMVarT = (liftIO.) . putMVar takeMVarT = liftIO . takeMVar readMVarT = liftIO . readMVar modifyUserTable fn = viewUsers >>= \mv -> liftIO $ modifyMVar_ mv (return . fn) viewHandle = threadHandle <$> ask viewUsers = userTableMV <$> ask userChat :: ServerApp () userChat = do name <- addUser echoLocal name h <- viewHandle (flip catchError) (\_ -> removeUser name) $ do echoLocal $ "Accepted " <> name forever $ getRemoteLine >>= broadcast (Client name) removeUser :: Text -> ServerApp () removeUser name = do echoLocal $ "Exception with " <> name <> ", removing from userTable" broadcast Server $ name <> " has left the server" modifyUserTable (M.delete name) addUser :: ServerApp Text addUser = do h <- viewHandle usersMV <- viewUsers echoRemote "Enter username" name <- T.filter (/='\r') <$> getRemoteLine userTable <- takeMVarT usersMV if name `M.member` userTable then do echoRemote "Username already exists!" putMVarT usersMV userTable addUser else do putMVarT usersMV (M.insert name h userTable) broadcast Server $ name <> " has joined the server" echoRemote "Welcome to the server!\n>> Other users:" readMVarT usersMV >>= mapM_ (echoRemote . ("*" <>) . fst) . filter ((/=name). fst) . M.toList return name broadcast :: Speaker -> Text -> ServerApp () broadcast user msg = viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList where f h = liftIO $ T.hPutStrLn h $ nm <> msg (fn, nm) = case user of Server -> (id, ">> ") Client t -> (filter ((/=t) . fst), t <> "> ") clientLoop socket users = do (h, _, _) <- accept socket hSetBuffering h LineBuffering forkIO $ runReaderT userChat (ThreadData h users) clientLoop socket users main = do server <- listenOn $ PortNumber 5002 T.putStrLn "Server started" newMVar (M.empty) >>= clientLoop server
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Write the same code in Go as shown below in Haskell.
import Network import System.IO import Control.Concurrent import qualified Data.Text as T import Data.Text (Text) import qualified Data.Text.IO as T import qualified Data.Map as M import Data.Map (Map) import Control.Monad.Reader import Control.Monad.Error import Control.Exception import Data.Monoid import Control.Applicative type ServerApp = ReaderT ThreadData IO data Speaker = Server | Client Text data ThreadData = ThreadData { threadHandle :: Handle , userTableMV :: MVar (Map Text Handle)} echoLocal = liftIO . T.putStrLn echoRemote = echoMessage . (">> "<>) echoMessage msg = viewHandle >>= \h -> liftIO $ T.hPutStrLn h msg getRemoteLine = viewHandle >>= liftIO . T.hGetLine putMVarT = (liftIO.) . putMVar takeMVarT = liftIO . takeMVar readMVarT = liftIO . readMVar modifyUserTable fn = viewUsers >>= \mv -> liftIO $ modifyMVar_ mv (return . fn) viewHandle = threadHandle <$> ask viewUsers = userTableMV <$> ask userChat :: ServerApp () userChat = do name <- addUser echoLocal name h <- viewHandle (flip catchError) (\_ -> removeUser name) $ do echoLocal $ "Accepted " <> name forever $ getRemoteLine >>= broadcast (Client name) removeUser :: Text -> ServerApp () removeUser name = do echoLocal $ "Exception with " <> name <> ", removing from userTable" broadcast Server $ name <> " has left the server" modifyUserTable (M.delete name) addUser :: ServerApp Text addUser = do h <- viewHandle usersMV <- viewUsers echoRemote "Enter username" name <- T.filter (/='\r') <$> getRemoteLine userTable <- takeMVarT usersMV if name `M.member` userTable then do echoRemote "Username already exists!" putMVarT usersMV userTable addUser else do putMVarT usersMV (M.insert name h userTable) broadcast Server $ name <> " has joined the server" echoRemote "Welcome to the server!\n>> Other users:" readMVarT usersMV >>= mapM_ (echoRemote . ("*" <>) . fst) . filter ((/=name). fst) . M.toList return name broadcast :: Speaker -> Text -> ServerApp () broadcast user msg = viewUsers >>= readMVarT >>= mapM_ (f . snd) . fn . M.toList where f h = liftIO $ T.hPutStrLn h $ nm <> msg (fn, nm) = case user of Server -> (id, ">> ") Client t -> (filter ((/=t) . fst), t <> "> ") clientLoop socket users = do (h, _, _) <- accept socket hSetBuffering h LineBuffering forkIO $ runReaderT userChat (ThreadData h users) clientLoop socket users main = do server <- listenOn $ PortNumber 5002 T.putStrLn "Server started" newMVar (M.empty) >>= clientLoop server
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Change the programming language of this snippet from Julia to C without modifying what it does.
using HttpServer using WebSockets const connections = Dict{Int,WebSocket}() const usernames = Dict{Int,String}() function decodeMessage( msg ) String(copy(msg)) end wsh = WebSocketHandler() do req, client global connections @show connections[client.id] = client println("req is $req") notifyonline = "Connection from user number $(client.id) is now online." for (k,v) in connections if k != client.id try write(v, notifyonline) catch continue end end end while true try msg = read(client) catch telloffline = "User $(usernames[client.id]) disconnected." println(telloffline, "(The client id was $(client.id).)") delete!(connections, client.id) if haskey(usernames, client.id) delete!(usernames, client.id) end for (k,v) in connections try write(v, telloffline) catch continue end end return end msg = decodeMessage(msg) if startswith(msg, "setusername:") println("SETTING USERNAME: $msg") usernames[client.id] = msg[13:end] notifyusername = "User number $(client.id) chose $(usernames[client.id]) as name handle." for (k,v) in connections try write(v, notifyusername) catch println("Caught exception writing to user $k") continue end end end if startswith(msg, "say:") println("EMITTING MESSAGE: $msg") for (k,v) in connections if k != client.id try write(v, (usernames[client.id] * ": " * msg[5:end])) catch println("Caught exception writing to user $k") continue end end end end end end onepage = readstring(Pkg.dir("WebSockets","examples","chat-client.html")) httph = HttpHandler() do req::Request, res::Response Response(onepage) end server = Server(httph, wsh) println("Chat server listening on 8000...") run(server,8000)
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
using HttpServer using WebSockets const connections = Dict{Int,WebSocket}() const usernames = Dict{Int,String}() function decodeMessage( msg ) String(copy(msg)) end wsh = WebSocketHandler() do req, client global connections @show connections[client.id] = client println("req is $req") notifyonline = "Connection from user number $(client.id) is now online." for (k,v) in connections if k != client.id try write(v, notifyonline) catch continue end end end while true try msg = read(client) catch telloffline = "User $(usernames[client.id]) disconnected." println(telloffline, "(The client id was $(client.id).)") delete!(connections, client.id) if haskey(usernames, client.id) delete!(usernames, client.id) end for (k,v) in connections try write(v, telloffline) catch continue end end return end msg = decodeMessage(msg) if startswith(msg, "setusername:") println("SETTING USERNAME: $msg") usernames[client.id] = msg[13:end] notifyusername = "User number $(client.id) chose $(usernames[client.id]) as name handle." for (k,v) in connections try write(v, notifyusername) catch println("Caught exception writing to user $k") continue end end end if startswith(msg, "say:") println("EMITTING MESSAGE: $msg") for (k,v) in connections if k != client.id try write(v, (usernames[client.id] * ": " * msg[5:end])) catch println("Caught exception writing to user $k") continue end end end end end end onepage = readstring(Pkg.dir("WebSockets","examples","chat-client.html")) httph = HttpHandler() do req::Request, res::Response Response(onepage) end server = Server(httph, wsh) println("Chat server listening on 8000...") run(server,8000)
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Change the programming language of this snippet from Julia to Java without modifying what it does.
using HttpServer using WebSockets const connections = Dict{Int,WebSocket}() const usernames = Dict{Int,String}() function decodeMessage( msg ) String(copy(msg)) end wsh = WebSocketHandler() do req, client global connections @show connections[client.id] = client println("req is $req") notifyonline = "Connection from user number $(client.id) is now online." for (k,v) in connections if k != client.id try write(v, notifyonline) catch continue end end end while true try msg = read(client) catch telloffline = "User $(usernames[client.id]) disconnected." println(telloffline, "(The client id was $(client.id).)") delete!(connections, client.id) if haskey(usernames, client.id) delete!(usernames, client.id) end for (k,v) in connections try write(v, telloffline) catch continue end end return end msg = decodeMessage(msg) if startswith(msg, "setusername:") println("SETTING USERNAME: $msg") usernames[client.id] = msg[13:end] notifyusername = "User number $(client.id) chose $(usernames[client.id]) as name handle." for (k,v) in connections try write(v, notifyusername) catch println("Caught exception writing to user $k") continue end end end if startswith(msg, "say:") println("EMITTING MESSAGE: $msg") for (k,v) in connections if k != client.id try write(v, (usernames[client.id] * ": " * msg[5:end])) catch println("Caught exception writing to user $k") continue end end end end end end onepage = readstring(Pkg.dir("WebSockets","examples","chat-client.html")) httph = HttpHandler() do req::Request, res::Response Response(onepage) end server = Server(httph, wsh) println("Chat server listening on 8000...") run(server,8000)
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Convert this Julia block to Python, preserving its control flow and logic.
using HttpServer using WebSockets const connections = Dict{Int,WebSocket}() const usernames = Dict{Int,String}() function decodeMessage( msg ) String(copy(msg)) end wsh = WebSocketHandler() do req, client global connections @show connections[client.id] = client println("req is $req") notifyonline = "Connection from user number $(client.id) is now online." for (k,v) in connections if k != client.id try write(v, notifyonline) catch continue end end end while true try msg = read(client) catch telloffline = "User $(usernames[client.id]) disconnected." println(telloffline, "(The client id was $(client.id).)") delete!(connections, client.id) if haskey(usernames, client.id) delete!(usernames, client.id) end for (k,v) in connections try write(v, telloffline) catch continue end end return end msg = decodeMessage(msg) if startswith(msg, "setusername:") println("SETTING USERNAME: $msg") usernames[client.id] = msg[13:end] notifyusername = "User number $(client.id) chose $(usernames[client.id]) as name handle." for (k,v) in connections try write(v, notifyusername) catch println("Caught exception writing to user $k") continue end end end if startswith(msg, "say:") println("EMITTING MESSAGE: $msg") for (k,v) in connections if k != client.id try write(v, (usernames[client.id] * ": " * msg[5:end])) catch println("Caught exception writing to user $k") continue end end end end end end onepage = readstring(Pkg.dir("WebSockets","examples","chat-client.html")) httph = HttpHandler() do req::Request, res::Response Response(onepage) end server = Server(httph, wsh) println("Chat server listening on 8000...") run(server,8000)
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Ensure the translated VB code behaves exactly like the original Julia snippet.
using HttpServer using WebSockets const connections = Dict{Int,WebSocket}() const usernames = Dict{Int,String}() function decodeMessage( msg ) String(copy(msg)) end wsh = WebSocketHandler() do req, client global connections @show connections[client.id] = client println("req is $req") notifyonline = "Connection from user number $(client.id) is now online." for (k,v) in connections if k != client.id try write(v, notifyonline) catch continue end end end while true try msg = read(client) catch telloffline = "User $(usernames[client.id]) disconnected." println(telloffline, "(The client id was $(client.id).)") delete!(connections, client.id) if haskey(usernames, client.id) delete!(usernames, client.id) end for (k,v) in connections try write(v, telloffline) catch continue end end return end msg = decodeMessage(msg) if startswith(msg, "setusername:") println("SETTING USERNAME: $msg") usernames[client.id] = msg[13:end] notifyusername = "User number $(client.id) chose $(usernames[client.id]) as name handle." for (k,v) in connections try write(v, notifyusername) catch println("Caught exception writing to user $k") continue end end end if startswith(msg, "say:") println("EMITTING MESSAGE: $msg") for (k,v) in connections if k != client.id try write(v, (usernames[client.id] * ": " * msg[5:end])) catch println("Caught exception writing to user $k") continue end end end end end end onepage = readstring(Pkg.dir("WebSockets","examples","chat-client.html")) httph = HttpHandler() do req::Request, res::Response Response(onepage) end server = Server(httph, wsh) println("Chat server listening on 8000...") run(server,8000)
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Generate a Go translation of this Julia snippet without changing its computational steps.
using HttpServer using WebSockets const connections = Dict{Int,WebSocket}() const usernames = Dict{Int,String}() function decodeMessage( msg ) String(copy(msg)) end wsh = WebSocketHandler() do req, client global connections @show connections[client.id] = client println("req is $req") notifyonline = "Connection from user number $(client.id) is now online." for (k,v) in connections if k != client.id try write(v, notifyonline) catch continue end end end while true try msg = read(client) catch telloffline = "User $(usernames[client.id]) disconnected." println(telloffline, "(The client id was $(client.id).)") delete!(connections, client.id) if haskey(usernames, client.id) delete!(usernames, client.id) end for (k,v) in connections try write(v, telloffline) catch continue end end return end msg = decodeMessage(msg) if startswith(msg, "setusername:") println("SETTING USERNAME: $msg") usernames[client.id] = msg[13:end] notifyusername = "User number $(client.id) chose $(usernames[client.id]) as name handle." for (k,v) in connections try write(v, notifyusername) catch println("Caught exception writing to user $k") continue end end end if startswith(msg, "say:") println("EMITTING MESSAGE: $msg") for (k,v) in connections if k != client.id try write(v, (usernames[client.id] * ": " * msg[5:end])) catch println("Caught exception writing to user $k") continue end end end end end end onepage = readstring(Pkg.dir("WebSockets","examples","chat-client.html")) httph = HttpHandler() do req::Request, res::Response Response(onepage) end server = Server(httph, wsh) println("Chat server listening on 8000...") run(server,8000)
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Port the provided Nim code into C while preserving the original functionality.
import asyncnet, asyncdispatch type Client = tuple socket: AsyncSocket name: string connected: bool var clients {.threadvar.}: seq[Client] proc sendOthers(client: Client, line: string) {.async.} = for c in clients: if c != client and c.connected: await c.socket.send(line & "\c\L") proc processClient(socket: AsyncSocket) {.async.} = await socket.send("Please enter your name: ") var client: Client = (socket, await socket.recvLine(), true) clients.add(client) asyncCheck client.sendOthers("+++ " & client.name & " arrived +++") while true: let line = await client.socket.recvLine() if line == "": asyncCheck client.sendOthers("--- " & client.name & " leaves ---") client.connected = false return asyncCheck client.sendOthers(client.name & "> " & line) proc serve() {.async.} = clients = @[] var server = newAsyncSocket() server.bindAddr(Port(4004)) server.listen() while true: let socket = await server.accept() asyncCheck processClient(socket) asyncCheck serve() runForever()
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Ensure the translated C# code behaves exactly like the original Nim snippet.
import asyncnet, asyncdispatch type Client = tuple socket: AsyncSocket name: string connected: bool var clients {.threadvar.}: seq[Client] proc sendOthers(client: Client, line: string) {.async.} = for c in clients: if c != client and c.connected: await c.socket.send(line & "\c\L") proc processClient(socket: AsyncSocket) {.async.} = await socket.send("Please enter your name: ") var client: Client = (socket, await socket.recvLine(), true) clients.add(client) asyncCheck client.sendOthers("+++ " & client.name & " arrived +++") while true: let line = await client.socket.recvLine() if line == "": asyncCheck client.sendOthers("--- " & client.name & " leaves ---") client.connected = false return asyncCheck client.sendOthers(client.name & "> " & line) proc serve() {.async.} = clients = @[] var server = newAsyncSocket() server.bindAddr(Port(4004)) server.listen() while true: let socket = await server.accept() asyncCheck processClient(socket) asyncCheck serve() runForever()
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Write the same algorithm in Java as shown in this Nim implementation.
import asyncnet, asyncdispatch type Client = tuple socket: AsyncSocket name: string connected: bool var clients {.threadvar.}: seq[Client] proc sendOthers(client: Client, line: string) {.async.} = for c in clients: if c != client and c.connected: await c.socket.send(line & "\c\L") proc processClient(socket: AsyncSocket) {.async.} = await socket.send("Please enter your name: ") var client: Client = (socket, await socket.recvLine(), true) clients.add(client) asyncCheck client.sendOthers("+++ " & client.name & " arrived +++") while true: let line = await client.socket.recvLine() if line == "": asyncCheck client.sendOthers("--- " & client.name & " leaves ---") client.connected = false return asyncCheck client.sendOthers(client.name & "> " & line) proc serve() {.async.} = clients = @[] var server = newAsyncSocket() server.bindAddr(Port(4004)) server.listen() while true: let socket = await server.accept() asyncCheck processClient(socket) asyncCheck serve() runForever()
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Write the same code in Python as shown below in Nim.
import asyncnet, asyncdispatch type Client = tuple socket: AsyncSocket name: string connected: bool var clients {.threadvar.}: seq[Client] proc sendOthers(client: Client, line: string) {.async.} = for c in clients: if c != client and c.connected: await c.socket.send(line & "\c\L") proc processClient(socket: AsyncSocket) {.async.} = await socket.send("Please enter your name: ") var client: Client = (socket, await socket.recvLine(), true) clients.add(client) asyncCheck client.sendOthers("+++ " & client.name & " arrived +++") while true: let line = await client.socket.recvLine() if line == "": asyncCheck client.sendOthers("--- " & client.name & " leaves ---") client.connected = false return asyncCheck client.sendOthers(client.name & "> " & line) proc serve() {.async.} = clients = @[] var server = newAsyncSocket() server.bindAddr(Port(4004)) server.listen() while true: let socket = await server.accept() asyncCheck processClient(socket) asyncCheck serve() runForever()
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Please provide an equivalent version of this Nim code in VB.
import asyncnet, asyncdispatch type Client = tuple socket: AsyncSocket name: string connected: bool var clients {.threadvar.}: seq[Client] proc sendOthers(client: Client, line: string) {.async.} = for c in clients: if c != client and c.connected: await c.socket.send(line & "\c\L") proc processClient(socket: AsyncSocket) {.async.} = await socket.send("Please enter your name: ") var client: Client = (socket, await socket.recvLine(), true) clients.add(client) asyncCheck client.sendOthers("+++ " & client.name & " arrived +++") while true: let line = await client.socket.recvLine() if line == "": asyncCheck client.sendOthers("--- " & client.name & " leaves ---") client.connected = false return asyncCheck client.sendOthers(client.name & "> " & line) proc serve() {.async.} = clients = @[] var server = newAsyncSocket() server.bindAddr(Port(4004)) server.listen() while true: let socket = await server.accept() asyncCheck processClient(socket) asyncCheck serve() runForever()
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Translate this program into Go but keep the logic exactly as in Nim.
import asyncnet, asyncdispatch type Client = tuple socket: AsyncSocket name: string connected: bool var clients {.threadvar.}: seq[Client] proc sendOthers(client: Client, line: string) {.async.} = for c in clients: if c != client and c.connected: await c.socket.send(line & "\c\L") proc processClient(socket: AsyncSocket) {.async.} = await socket.send("Please enter your name: ") var client: Client = (socket, await socket.recvLine(), true) clients.add(client) asyncCheck client.sendOthers("+++ " & client.name & " arrived +++") while true: let line = await client.socket.recvLine() if line == "": asyncCheck client.sendOthers("--- " & client.name & " leaves ---") client.connected = false return asyncCheck client.sendOthers(client.name & "> " & line) proc serve() {.async.} = clients = @[] var server = newAsyncSocket() server.bindAddr(Port(4004)) server.listen() while true: let socket = await server.accept() asyncCheck processClient(socket) asyncCheck serve() runForever()
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Rewrite this program in C while keeping its functionality equivalent to the Perl version.
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); }
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Port the following code from Perl to C# with equivalent syntax and logic.
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); }
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Rewrite the snippet below in Java so it works the same as the original Perl code.
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); }
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Ensure the translated Python code behaves exactly like the original Perl snippet.
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); }
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Rewrite the snippet below in VB so it works the same as the original Perl code.
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); }
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Write a version of this Perl function in Go with identical behavior.
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); }
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Rewrite the snippet below in C so it works the same as the original R code.
chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) while (in_queue(server)) sockets <- new_socket_entry(server, sockets) sockets <- check_messages(sockets) if (nrow(sockets) == 0) next if (all(!sockets$message_ready)) next sockets <- read_messages(sockets) sockets <- drop_dead(sockets) if (nrow(sockets) == 0) next sockets <- update_nicknames(sockets) sockets <- send_messages(sockets) } } check_messages <- function(sockets) { if (nrow(sockets) != 0) sockets$message_ready <- socketSelect(sockets$conn, timeout = 0) sockets } drop_dead <- function(sockets) { lapply(with(sockets, conn[!alive]), close) dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive]) sockets <- sockets[sockets$alive, ] if (length(dropped) != 0) { send_named(sockets, paste0(dropped, " has disconnected.")) } sockets } in_queue <- function(server) socketSelect(list(server), timeout = 0) is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == "" message_exists <- function(sockets) !is.na(sockets$message) new_row <- function(df) { df[nrow(df) + 1, ] <- NA df } new_socket_entry <- function(server, sockets) { sockets <- new_row(sockets) n <- nrow(sockets) within(sockets, { conn[[n]] <- new_user(server) alive[n] <- TRUE message_ready[n] <- FALSE }) } new_user <- function(server) { conn <- socketAccept(server) writeLines("Hello! Please enter a nickname.", conn) conn } nickname_exists <- function(sockets) !is.na(sockets$nickname) read_messages <- function(sockets) { if (all(!sockets$message_ready)) return(sockets) msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1) empty_msgs <- sapply(msgs, identical, character(0)) sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE) msgs <- unlist(ifelse(empty_msgs, NA, msgs)) within(sockets, message[message_ready] <- msgs) } send_messages <- function(sockets) { named_message <- message_exists(sockets) & nickname_exists(sockets) if (all(!named_message)) return(sockets) rows <- which(named_message) socksub <- sockets[rows, ] time <- format(Sys.time(), "[%H:%M:%S] ") with(socksub, send_named(sockets, paste0(time, nickname, ": ", message))) within(sockets, message[rows] <- NA) } send_named <- function(sockets, msg) { has_nickname <- nickname_exists(sockets) invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg)) } start_chat_server <- function(port = 50525) { server <- serverSocket(port) on.exit(closeAllConnections()) sockets <- data.frame(conn = I(list()), nickname = character(), message = character(), alive = logical(), message_ready = logical()) chat_loop(server, sockets) } update_nicknames <- function(sockets) { sent_nickname <- message_exists(sockets) & !nickname_exists(sockets) nickname_valid <- is_valid_name(sockets$message) if (all(!sent_nickname)) return(sockets) is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) & !is.na(message)) sent_ok <- sent_nickname & nickname_valid & !is_taken sockets <- within(sockets, { nickname[sent_ok] <- message[sent_ok] message[sent_nickname] <- NA lapply(conn[sent_nickname & !nickname_valid], writeLines, text = "Alphanumeric characters only. Try again.") lapply(conn[is_taken], writeLines, text = "Name already taken. Try again.") }) if (any(sent_ok)) send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected.")) sockets } start_chat_server()
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Keep all operations the same but rewrite the snippet in C#.
chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) while (in_queue(server)) sockets <- new_socket_entry(server, sockets) sockets <- check_messages(sockets) if (nrow(sockets) == 0) next if (all(!sockets$message_ready)) next sockets <- read_messages(sockets) sockets <- drop_dead(sockets) if (nrow(sockets) == 0) next sockets <- update_nicknames(sockets) sockets <- send_messages(sockets) } } check_messages <- function(sockets) { if (nrow(sockets) != 0) sockets$message_ready <- socketSelect(sockets$conn, timeout = 0) sockets } drop_dead <- function(sockets) { lapply(with(sockets, conn[!alive]), close) dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive]) sockets <- sockets[sockets$alive, ] if (length(dropped) != 0) { send_named(sockets, paste0(dropped, " has disconnected.")) } sockets } in_queue <- function(server) socketSelect(list(server), timeout = 0) is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == "" message_exists <- function(sockets) !is.na(sockets$message) new_row <- function(df) { df[nrow(df) + 1, ] <- NA df } new_socket_entry <- function(server, sockets) { sockets <- new_row(sockets) n <- nrow(sockets) within(sockets, { conn[[n]] <- new_user(server) alive[n] <- TRUE message_ready[n] <- FALSE }) } new_user <- function(server) { conn <- socketAccept(server) writeLines("Hello! Please enter a nickname.", conn) conn } nickname_exists <- function(sockets) !is.na(sockets$nickname) read_messages <- function(sockets) { if (all(!sockets$message_ready)) return(sockets) msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1) empty_msgs <- sapply(msgs, identical, character(0)) sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE) msgs <- unlist(ifelse(empty_msgs, NA, msgs)) within(sockets, message[message_ready] <- msgs) } send_messages <- function(sockets) { named_message <- message_exists(sockets) & nickname_exists(sockets) if (all(!named_message)) return(sockets) rows <- which(named_message) socksub <- sockets[rows, ] time <- format(Sys.time(), "[%H:%M:%S] ") with(socksub, send_named(sockets, paste0(time, nickname, ": ", message))) within(sockets, message[rows] <- NA) } send_named <- function(sockets, msg) { has_nickname <- nickname_exists(sockets) invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg)) } start_chat_server <- function(port = 50525) { server <- serverSocket(port) on.exit(closeAllConnections()) sockets <- data.frame(conn = I(list()), nickname = character(), message = character(), alive = logical(), message_ready = logical()) chat_loop(server, sockets) } update_nicknames <- function(sockets) { sent_nickname <- message_exists(sockets) & !nickname_exists(sockets) nickname_valid <- is_valid_name(sockets$message) if (all(!sent_nickname)) return(sockets) is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) & !is.na(message)) sent_ok <- sent_nickname & nickname_valid & !is_taken sockets <- within(sockets, { nickname[sent_ok] <- message[sent_ok] message[sent_nickname] <- NA lapply(conn[sent_nickname & !nickname_valid], writeLines, text = "Alphanumeric characters only. Try again.") lapply(conn[is_taken], writeLines, text = "Name already taken. Try again.") }) if (any(sent_ok)) send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected.")) sockets } start_chat_server()
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Maintain the same structure and functionality when rewriting this code in Java.
chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) while (in_queue(server)) sockets <- new_socket_entry(server, sockets) sockets <- check_messages(sockets) if (nrow(sockets) == 0) next if (all(!sockets$message_ready)) next sockets <- read_messages(sockets) sockets <- drop_dead(sockets) if (nrow(sockets) == 0) next sockets <- update_nicknames(sockets) sockets <- send_messages(sockets) } } check_messages <- function(sockets) { if (nrow(sockets) != 0) sockets$message_ready <- socketSelect(sockets$conn, timeout = 0) sockets } drop_dead <- function(sockets) { lapply(with(sockets, conn[!alive]), close) dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive]) sockets <- sockets[sockets$alive, ] if (length(dropped) != 0) { send_named(sockets, paste0(dropped, " has disconnected.")) } sockets } in_queue <- function(server) socketSelect(list(server), timeout = 0) is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == "" message_exists <- function(sockets) !is.na(sockets$message) new_row <- function(df) { df[nrow(df) + 1, ] <- NA df } new_socket_entry <- function(server, sockets) { sockets <- new_row(sockets) n <- nrow(sockets) within(sockets, { conn[[n]] <- new_user(server) alive[n] <- TRUE message_ready[n] <- FALSE }) } new_user <- function(server) { conn <- socketAccept(server) writeLines("Hello! Please enter a nickname.", conn) conn } nickname_exists <- function(sockets) !is.na(sockets$nickname) read_messages <- function(sockets) { if (all(!sockets$message_ready)) return(sockets) msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1) empty_msgs <- sapply(msgs, identical, character(0)) sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE) msgs <- unlist(ifelse(empty_msgs, NA, msgs)) within(sockets, message[message_ready] <- msgs) } send_messages <- function(sockets) { named_message <- message_exists(sockets) & nickname_exists(sockets) if (all(!named_message)) return(sockets) rows <- which(named_message) socksub <- sockets[rows, ] time <- format(Sys.time(), "[%H:%M:%S] ") with(socksub, send_named(sockets, paste0(time, nickname, ": ", message))) within(sockets, message[rows] <- NA) } send_named <- function(sockets, msg) { has_nickname <- nickname_exists(sockets) invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg)) } start_chat_server <- function(port = 50525) { server <- serverSocket(port) on.exit(closeAllConnections()) sockets <- data.frame(conn = I(list()), nickname = character(), message = character(), alive = logical(), message_ready = logical()) chat_loop(server, sockets) } update_nicknames <- function(sockets) { sent_nickname <- message_exists(sockets) & !nickname_exists(sockets) nickname_valid <- is_valid_name(sockets$message) if (all(!sent_nickname)) return(sockets) is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) & !is.na(message)) sent_ok <- sent_nickname & nickname_valid & !is_taken sockets <- within(sockets, { nickname[sent_ok] <- message[sent_ok] message[sent_nickname] <- NA lapply(conn[sent_nickname & !nickname_valid], writeLines, text = "Alphanumeric characters only. Try again.") lapply(conn[is_taken], writeLines, text = "Name already taken. Try again.") }) if (any(sent_ok)) send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected.")) sockets } start_chat_server()
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Produce a language-to-language conversion: from R to Python, same semantics.
chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) while (in_queue(server)) sockets <- new_socket_entry(server, sockets) sockets <- check_messages(sockets) if (nrow(sockets) == 0) next if (all(!sockets$message_ready)) next sockets <- read_messages(sockets) sockets <- drop_dead(sockets) if (nrow(sockets) == 0) next sockets <- update_nicknames(sockets) sockets <- send_messages(sockets) } } check_messages <- function(sockets) { if (nrow(sockets) != 0) sockets$message_ready <- socketSelect(sockets$conn, timeout = 0) sockets } drop_dead <- function(sockets) { lapply(with(sockets, conn[!alive]), close) dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive]) sockets <- sockets[sockets$alive, ] if (length(dropped) != 0) { send_named(sockets, paste0(dropped, " has disconnected.")) } sockets } in_queue <- function(server) socketSelect(list(server), timeout = 0) is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == "" message_exists <- function(sockets) !is.na(sockets$message) new_row <- function(df) { df[nrow(df) + 1, ] <- NA df } new_socket_entry <- function(server, sockets) { sockets <- new_row(sockets) n <- nrow(sockets) within(sockets, { conn[[n]] <- new_user(server) alive[n] <- TRUE message_ready[n] <- FALSE }) } new_user <- function(server) { conn <- socketAccept(server) writeLines("Hello! Please enter a nickname.", conn) conn } nickname_exists <- function(sockets) !is.na(sockets$nickname) read_messages <- function(sockets) { if (all(!sockets$message_ready)) return(sockets) msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1) empty_msgs <- sapply(msgs, identical, character(0)) sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE) msgs <- unlist(ifelse(empty_msgs, NA, msgs)) within(sockets, message[message_ready] <- msgs) } send_messages <- function(sockets) { named_message <- message_exists(sockets) & nickname_exists(sockets) if (all(!named_message)) return(sockets) rows <- which(named_message) socksub <- sockets[rows, ] time <- format(Sys.time(), "[%H:%M:%S] ") with(socksub, send_named(sockets, paste0(time, nickname, ": ", message))) within(sockets, message[rows] <- NA) } send_named <- function(sockets, msg) { has_nickname <- nickname_exists(sockets) invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg)) } start_chat_server <- function(port = 50525) { server <- serverSocket(port) on.exit(closeAllConnections()) sockets <- data.frame(conn = I(list()), nickname = character(), message = character(), alive = logical(), message_ready = logical()) chat_loop(server, sockets) } update_nicknames <- function(sockets) { sent_nickname <- message_exists(sockets) & !nickname_exists(sockets) nickname_valid <- is_valid_name(sockets$message) if (all(!sent_nickname)) return(sockets) is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) & !is.na(message)) sent_ok <- sent_nickname & nickname_valid & !is_taken sockets <- within(sockets, { nickname[sent_ok] <- message[sent_ok] message[sent_nickname] <- NA lapply(conn[sent_nickname & !nickname_valid], writeLines, text = "Alphanumeric characters only. Try again.") lapply(conn[is_taken], writeLines, text = "Name already taken. Try again.") }) if (any(sent_ok)) send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected.")) sockets } start_chat_server()
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Port the provided R code into VB while preserving the original functionality.
chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) while (in_queue(server)) sockets <- new_socket_entry(server, sockets) sockets <- check_messages(sockets) if (nrow(sockets) == 0) next if (all(!sockets$message_ready)) next sockets <- read_messages(sockets) sockets <- drop_dead(sockets) if (nrow(sockets) == 0) next sockets <- update_nicknames(sockets) sockets <- send_messages(sockets) } } check_messages <- function(sockets) { if (nrow(sockets) != 0) sockets$message_ready <- socketSelect(sockets$conn, timeout = 0) sockets } drop_dead <- function(sockets) { lapply(with(sockets, conn[!alive]), close) dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive]) sockets <- sockets[sockets$alive, ] if (length(dropped) != 0) { send_named(sockets, paste0(dropped, " has disconnected.")) } sockets } in_queue <- function(server) socketSelect(list(server), timeout = 0) is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == "" message_exists <- function(sockets) !is.na(sockets$message) new_row <- function(df) { df[nrow(df) + 1, ] <- NA df } new_socket_entry <- function(server, sockets) { sockets <- new_row(sockets) n <- nrow(sockets) within(sockets, { conn[[n]] <- new_user(server) alive[n] <- TRUE message_ready[n] <- FALSE }) } new_user <- function(server) { conn <- socketAccept(server) writeLines("Hello! Please enter a nickname.", conn) conn } nickname_exists <- function(sockets) !is.na(sockets$nickname) read_messages <- function(sockets) { if (all(!sockets$message_ready)) return(sockets) msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1) empty_msgs <- sapply(msgs, identical, character(0)) sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE) msgs <- unlist(ifelse(empty_msgs, NA, msgs)) within(sockets, message[message_ready] <- msgs) } send_messages <- function(sockets) { named_message <- message_exists(sockets) & nickname_exists(sockets) if (all(!named_message)) return(sockets) rows <- which(named_message) socksub <- sockets[rows, ] time <- format(Sys.time(), "[%H:%M:%S] ") with(socksub, send_named(sockets, paste0(time, nickname, ": ", message))) within(sockets, message[rows] <- NA) } send_named <- function(sockets, msg) { has_nickname <- nickname_exists(sockets) invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg)) } start_chat_server <- function(port = 50525) { server <- serverSocket(port) on.exit(closeAllConnections()) sockets <- data.frame(conn = I(list()), nickname = character(), message = character(), alive = logical(), message_ready = logical()) chat_loop(server, sockets) } update_nicknames <- function(sockets) { sent_nickname <- message_exists(sockets) & !nickname_exists(sockets) nickname_valid <- is_valid_name(sockets$message) if (all(!sent_nickname)) return(sockets) is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) & !is.na(message)) sent_ok <- sent_nickname & nickname_valid & !is_taken sockets <- within(sockets, { nickname[sent_ok] <- message[sent_ok] message[sent_nickname] <- NA lapply(conn[sent_nickname & !nickname_valid], writeLines, text = "Alphanumeric characters only. Try again.") lapply(conn[is_taken], writeLines, text = "Name already taken. Try again.") }) if (any(sent_ok)) send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected.")) sockets } start_chat_server()
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Preserve the algorithm and functionality while converting the code from R to Go.
chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) while (in_queue(server)) sockets <- new_socket_entry(server, sockets) sockets <- check_messages(sockets) if (nrow(sockets) == 0) next if (all(!sockets$message_ready)) next sockets <- read_messages(sockets) sockets <- drop_dead(sockets) if (nrow(sockets) == 0) next sockets <- update_nicknames(sockets) sockets <- send_messages(sockets) } } check_messages <- function(sockets) { if (nrow(sockets) != 0) sockets$message_ready <- socketSelect(sockets$conn, timeout = 0) sockets } drop_dead <- function(sockets) { lapply(with(sockets, conn[!alive]), close) dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive]) sockets <- sockets[sockets$alive, ] if (length(dropped) != 0) { send_named(sockets, paste0(dropped, " has disconnected.")) } sockets } in_queue <- function(server) socketSelect(list(server), timeout = 0) is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == "" message_exists <- function(sockets) !is.na(sockets$message) new_row <- function(df) { df[nrow(df) + 1, ] <- NA df } new_socket_entry <- function(server, sockets) { sockets <- new_row(sockets) n <- nrow(sockets) within(sockets, { conn[[n]] <- new_user(server) alive[n] <- TRUE message_ready[n] <- FALSE }) } new_user <- function(server) { conn <- socketAccept(server) writeLines("Hello! Please enter a nickname.", conn) conn } nickname_exists <- function(sockets) !is.na(sockets$nickname) read_messages <- function(sockets) { if (all(!sockets$message_ready)) return(sockets) msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1) empty_msgs <- sapply(msgs, identical, character(0)) sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE) msgs <- unlist(ifelse(empty_msgs, NA, msgs)) within(sockets, message[message_ready] <- msgs) } send_messages <- function(sockets) { named_message <- message_exists(sockets) & nickname_exists(sockets) if (all(!named_message)) return(sockets) rows <- which(named_message) socksub <- sockets[rows, ] time <- format(Sys.time(), "[%H:%M:%S] ") with(socksub, send_named(sockets, paste0(time, nickname, ": ", message))) within(sockets, message[rows] <- NA) } send_named <- function(sockets, msg) { has_nickname <- nickname_exists(sockets) invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg)) } start_chat_server <- function(port = 50525) { server <- serverSocket(port) on.exit(closeAllConnections()) sockets <- data.frame(conn = I(list()), nickname = character(), message = character(), alive = logical(), message_ready = logical()) chat_loop(server, sockets) } update_nicknames <- function(sockets) { sent_nickname <- message_exists(sockets) & !nickname_exists(sockets) nickname_valid <- is_valid_name(sockets$message) if (all(!sent_nickname)) return(sockets) is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) & !is.na(message)) sent_ok <- sent_nickname & nickname_valid & !is_taken sockets <- within(sockets, { nickname[sent_ok] <- message[sent_ok] message[sent_nickname] <- NA lapply(conn[sent_nickname & !nickname_valid], writeLines, text = "Alphanumeric characters only. Try again.") lapply(conn[is_taken], writeLines, text = "Name already taken. Try again.") }) if (any(sent_ok)) send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected.")) sockets } start_chat_server()
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Rewrite this program in C while keeping its functionality equivalent to the Racket version.
#lang racket (define outs (list (current-output-port))) (define ((tell-all who o) line) (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c))) (define ((client i o)) (define nick (begin (display "Nick: " o) (read-line i))) (define tell (tell-all nick o)) (let loop ([line "(joined)"]) (if (eof-object? line) (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) (begin (tell line) (loop (read-line i)))))) (define (chat-server listener) (define-values [i o] (tcp-accept listener)) (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) (thread (client i o)) (set! outs (cons o outs)) (chat-server listener)) (void (thread (λ() (chat-server (tcp-listen 12321))))) ((client (current-input-port) (current-output-port)))
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Generate an equivalent C# version of this Racket code.
#lang racket (define outs (list (current-output-port))) (define ((tell-all who o) line) (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c))) (define ((client i o)) (define nick (begin (display "Nick: " o) (read-line i))) (define tell (tell-all nick o)) (let loop ([line "(joined)"]) (if (eof-object? line) (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) (begin (tell line) (loop (read-line i)))))) (define (chat-server listener) (define-values [i o] (tcp-accept listener)) (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) (thread (client i o)) (set! outs (cons o outs)) (chat-server listener)) (void (thread (λ() (chat-server (tcp-listen 12321))))) ((client (current-input-port) (current-output-port)))
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Change the following Racket code into Java without altering its purpose.
#lang racket (define outs (list (current-output-port))) (define ((tell-all who o) line) (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c))) (define ((client i o)) (define nick (begin (display "Nick: " o) (read-line i))) (define tell (tell-all nick o)) (let loop ([line "(joined)"]) (if (eof-object? line) (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) (begin (tell line) (loop (read-line i)))))) (define (chat-server listener) (define-values [i o] (tcp-accept listener)) (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) (thread (client i o)) (set! outs (cons o outs)) (chat-server listener)) (void (thread (λ() (chat-server (tcp-listen 12321))))) ((client (current-input-port) (current-output-port)))
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Produce a language-to-language conversion: from Racket to Python, same semantics.
#lang racket (define outs (list (current-output-port))) (define ((tell-all who o) line) (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c))) (define ((client i o)) (define nick (begin (display "Nick: " o) (read-line i))) (define tell (tell-all nick o)) (let loop ([line "(joined)"]) (if (eof-object? line) (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) (begin (tell line) (loop (read-line i)))))) (define (chat-server listener) (define-values [i o] (tcp-accept listener)) (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) (thread (client i o)) (set! outs (cons o outs)) (chat-server listener)) (void (thread (λ() (chat-server (tcp-listen 12321))))) ((client (current-input-port) (current-output-port)))
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Translate this program into VB but keep the logic exactly as in Racket.
#lang racket (define outs (list (current-output-port))) (define ((tell-all who o) line) (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c))) (define ((client i o)) (define nick (begin (display "Nick: " o) (read-line i))) (define tell (tell-all nick o)) (let loop ([line "(joined)"]) (if (eof-object? line) (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) (begin (tell line) (loop (read-line i)))))) (define (chat-server listener) (define-values [i o] (tcp-accept listener)) (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) (thread (client i o)) (set! outs (cons o outs)) (chat-server listener)) (void (thread (λ() (chat-server (tcp-listen 12321))))) ((client (current-input-port) (current-output-port)))
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Translate this program into Go but keep the logic exactly as in Racket.
#lang racket (define outs (list (current-output-port))) (define ((tell-all who o) line) (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c))) (define ((client i o)) (define nick (begin (display "Nick: " o) (read-line i))) (define tell (tell-all nick o)) (let loop ([line "(joined)"]) (if (eof-object? line) (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) (begin (tell line) (loop (read-line i)))))) (define (chat-server listener) (define-values [i o] (tcp-accept listener)) (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) (thread (client i o)) (set! outs (cons o outs)) (chat-server listener)) (void (thread (λ() (chat-server (tcp-listen 12321))))) ((client (current-input-port) (current-output-port)))
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Change the following Ruby code into C without altering its purpose.
require 'gserver' class ChatServer < GServer def initialize *args super @chatters = [] @mutex = Mutex.new end def broadcast message, sender = nil message = message.strip << "\r\n" @mutex.synchronize do @chatters.each do |chatter| begin chatter.print message unless chatter == sender rescue @chatters.delete chatter end end end end def serve io io.print 'Name: ' name = io.gets return if name.nil? name.strip! broadcast "--+ @mutex.synchronize do @chatters << io end loop do message = io.gets if message broadcast " else break end end broadcast "--+ end end ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Write a version of this Ruby function in C# with identical behavior.
require 'gserver' class ChatServer < GServer def initialize *args super @chatters = [] @mutex = Mutex.new end def broadcast message, sender = nil message = message.strip << "\r\n" @mutex.synchronize do @chatters.each do |chatter| begin chatter.print message unless chatter == sender rescue @chatters.delete chatter end end end end def serve io io.print 'Name: ' name = io.gets return if name.nil? name.strip! broadcast "--+ @mutex.synchronize do @chatters << io end loop do message = io.gets if message broadcast " else break end end broadcast "--+ end end ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Convert this Ruby snippet to Java and keep its semantics consistent.
require 'gserver' class ChatServer < GServer def initialize *args super @chatters = [] @mutex = Mutex.new end def broadcast message, sender = nil message = message.strip << "\r\n" @mutex.synchronize do @chatters.each do |chatter| begin chatter.print message unless chatter == sender rescue @chatters.delete chatter end end end end def serve io io.print 'Name: ' name = io.gets return if name.nil? name.strip! broadcast "--+ @mutex.synchronize do @chatters << io end loop do message = io.gets if message broadcast " else break end end broadcast "--+ end end ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Translate this program into Python but keep the logic exactly as in Ruby.
require 'gserver' class ChatServer < GServer def initialize *args super @chatters = [] @mutex = Mutex.new end def broadcast message, sender = nil message = message.strip << "\r\n" @mutex.synchronize do @chatters.each do |chatter| begin chatter.print message unless chatter == sender rescue @chatters.delete chatter end end end end def serve io io.print 'Name: ' name = io.gets return if name.nil? name.strip! broadcast "--+ @mutex.synchronize do @chatters << io end loop do message = io.gets if message broadcast " else break end end broadcast "--+ end end ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Translate the given Ruby code snippet into VB without altering its behavior.
require 'gserver' class ChatServer < GServer def initialize *args super @chatters = [] @mutex = Mutex.new end def broadcast message, sender = nil message = message.strip << "\r\n" @mutex.synchronize do @chatters.each do |chatter| begin chatter.print message unless chatter == sender rescue @chatters.delete chatter end end end end def serve io io.print 'Name: ' name = io.gets return if name.nil? name.strip! broadcast "--+ @mutex.synchronize do @chatters << io end loop do message = io.gets if message broadcast " else break end end broadcast "--+ end end ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Produce a functionally identical Go code for the snippet given in Ruby.
require 'gserver' class ChatServer < GServer def initialize *args super @chatters = [] @mutex = Mutex.new end def broadcast message, sender = nil message = message.strip << "\r\n" @mutex.synchronize do @chatters.each do |chatter| begin chatter.print message unless chatter == sender rescue @chatters.delete chatter end end end end def serve io io.print 'Name: ' name = io.gets return if name.nil? name.strip! broadcast "--+ @mutex.synchronize do @chatters << io end loop do message = io.gets if message broadcast " else break end end broadcast "--+ end end ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Rewrite this program in C while keeping its functionality equivalent to the Scala version.
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections class ChatServer private constructor(private val port: Int) : Runnable { private val clients = ArrayList<Client>() private val onlineListCSV: String @Synchronized get() { val sb = StringBuilder() sb.append(clients.size).append(" user(s) online: ") for (i in clients.indices) { sb.append(if (i > 0) ", " else "").append(clients[i].clientName) } return sb.toString() } override fun run() { try { val ss = ServerSocket(port) while (true) { val s = ss.accept() Thread(Client(s)).start() } } catch (e: Exception) { e.printStackTrace() } } @Synchronized private fun registerClient(client: Client): Boolean { for (otherClient in clients) { if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) { return false } } clients.add(client) return true } private fun deRegisterClient(client: Client) { var wasRegistered = false synchronized(this) { wasRegistered = clients.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private fun broadcast(fromClient: Client, msg: String) { var clients: List<Client> = Collections.emptyList() synchronized(this) { clients = ArrayList(this.clients) } for (client in clients) { if (client.equals(fromClient)) { continue } try { client.write(msg + "\r\n") } catch (e: Exception) { e.printStackTrace() } } } inner class Client internal constructor(private var socket: Socket?) : Runnable { private var output: Writer? = null var clientName: String? = null override fun run() { try { socket!!.sendBufferSize = 16384 socket!!.tcpNoDelay = true val input = BufferedReader(InputStreamReader(socket!!.getInputStream())) output = OutputStreamWriter(socket!!.getOutputStream()) write("Please enter your name: ") var line: String while (true) { line = input.readLine() if (null == line) { break } if (clientName == null) { line = line.trim { it <= ' ' } if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(onlineListCSV + "\r\n") broadcast(this, "+++ $clientName arrived +++") continue } if (line.equals("/quit", ignoreCase = true)) { return } broadcast(this, "$clientName> $line") } } catch (e: Exception) { e.printStackTrace() } finally { deRegisterClient(this) output = null try { socket!!.close() } catch (e: Exception) { e.printStackTrace() } socket = null } } @Throws(IOException::class) internal fun write(msg: String) { output!!.write(msg) output!!.flush() } internal fun equals(client: Client?): Boolean { return (client != null && clientName != null && client.clientName != null && clientName == client.clientName) } } companion object { @JvmStatic fun main(args: Array<String>) { var port = 4004 if (args.isNotEmpty()) { port = Integer.parseInt(args[0]) } ChatServer(port).run() } } }
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Ensure the translated C# code behaves exactly like the original Scala snippet.
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections class ChatServer private constructor(private val port: Int) : Runnable { private val clients = ArrayList<Client>() private val onlineListCSV: String @Synchronized get() { val sb = StringBuilder() sb.append(clients.size).append(" user(s) online: ") for (i in clients.indices) { sb.append(if (i > 0) ", " else "").append(clients[i].clientName) } return sb.toString() } override fun run() { try { val ss = ServerSocket(port) while (true) { val s = ss.accept() Thread(Client(s)).start() } } catch (e: Exception) { e.printStackTrace() } } @Synchronized private fun registerClient(client: Client): Boolean { for (otherClient in clients) { if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) { return false } } clients.add(client) return true } private fun deRegisterClient(client: Client) { var wasRegistered = false synchronized(this) { wasRegistered = clients.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private fun broadcast(fromClient: Client, msg: String) { var clients: List<Client> = Collections.emptyList() synchronized(this) { clients = ArrayList(this.clients) } for (client in clients) { if (client.equals(fromClient)) { continue } try { client.write(msg + "\r\n") } catch (e: Exception) { e.printStackTrace() } } } inner class Client internal constructor(private var socket: Socket?) : Runnable { private var output: Writer? = null var clientName: String? = null override fun run() { try { socket!!.sendBufferSize = 16384 socket!!.tcpNoDelay = true val input = BufferedReader(InputStreamReader(socket!!.getInputStream())) output = OutputStreamWriter(socket!!.getOutputStream()) write("Please enter your name: ") var line: String while (true) { line = input.readLine() if (null == line) { break } if (clientName == null) { line = line.trim { it <= ' ' } if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(onlineListCSV + "\r\n") broadcast(this, "+++ $clientName arrived +++") continue } if (line.equals("/quit", ignoreCase = true)) { return } broadcast(this, "$clientName> $line") } } catch (e: Exception) { e.printStackTrace() } finally { deRegisterClient(this) output = null try { socket!!.close() } catch (e: Exception) { e.printStackTrace() } socket = null } } @Throws(IOException::class) internal fun write(msg: String) { output!!.write(msg) output!!.flush() } internal fun equals(client: Client?): Boolean { return (client != null && clientName != null && client.clientName != null && clientName == client.clientName) } } companion object { @JvmStatic fun main(args: Array<String>) { var port = 4004 if (args.isNotEmpty()) { port = Integer.parseInt(args[0]) } ChatServer(port).run() } } }
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Can you help me rewrite this code in Java instead of Scala, keeping it the same logically?
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections class ChatServer private constructor(private val port: Int) : Runnable { private val clients = ArrayList<Client>() private val onlineListCSV: String @Synchronized get() { val sb = StringBuilder() sb.append(clients.size).append(" user(s) online: ") for (i in clients.indices) { sb.append(if (i > 0) ", " else "").append(clients[i].clientName) } return sb.toString() } override fun run() { try { val ss = ServerSocket(port) while (true) { val s = ss.accept() Thread(Client(s)).start() } } catch (e: Exception) { e.printStackTrace() } } @Synchronized private fun registerClient(client: Client): Boolean { for (otherClient in clients) { if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) { return false } } clients.add(client) return true } private fun deRegisterClient(client: Client) { var wasRegistered = false synchronized(this) { wasRegistered = clients.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private fun broadcast(fromClient: Client, msg: String) { var clients: List<Client> = Collections.emptyList() synchronized(this) { clients = ArrayList(this.clients) } for (client in clients) { if (client.equals(fromClient)) { continue } try { client.write(msg + "\r\n") } catch (e: Exception) { e.printStackTrace() } } } inner class Client internal constructor(private var socket: Socket?) : Runnable { private var output: Writer? = null var clientName: String? = null override fun run() { try { socket!!.sendBufferSize = 16384 socket!!.tcpNoDelay = true val input = BufferedReader(InputStreamReader(socket!!.getInputStream())) output = OutputStreamWriter(socket!!.getOutputStream()) write("Please enter your name: ") var line: String while (true) { line = input.readLine() if (null == line) { break } if (clientName == null) { line = line.trim { it <= ' ' } if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(onlineListCSV + "\r\n") broadcast(this, "+++ $clientName arrived +++") continue } if (line.equals("/quit", ignoreCase = true)) { return } broadcast(this, "$clientName> $line") } } catch (e: Exception) { e.printStackTrace() } finally { deRegisterClient(this) output = null try { socket!!.close() } catch (e: Exception) { e.printStackTrace() } socket = null } } @Throws(IOException::class) internal fun write(msg: String) { output!!.write(msg) output!!.flush() } internal fun equals(client: Client?): Boolean { return (client != null && clientName != null && client.clientName != null && clientName == client.clientName) } } companion object { @JvmStatic fun main(args: Array<String>) { var port = 4004 if (args.isNotEmpty()) { port = Integer.parseInt(args[0]) } ChatServer(port).run() } } }
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Generate a Python translation of this Scala snippet without changing its computational steps.
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections class ChatServer private constructor(private val port: Int) : Runnable { private val clients = ArrayList<Client>() private val onlineListCSV: String @Synchronized get() { val sb = StringBuilder() sb.append(clients.size).append(" user(s) online: ") for (i in clients.indices) { sb.append(if (i > 0) ", " else "").append(clients[i].clientName) } return sb.toString() } override fun run() { try { val ss = ServerSocket(port) while (true) { val s = ss.accept() Thread(Client(s)).start() } } catch (e: Exception) { e.printStackTrace() } } @Synchronized private fun registerClient(client: Client): Boolean { for (otherClient in clients) { if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) { return false } } clients.add(client) return true } private fun deRegisterClient(client: Client) { var wasRegistered = false synchronized(this) { wasRegistered = clients.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private fun broadcast(fromClient: Client, msg: String) { var clients: List<Client> = Collections.emptyList() synchronized(this) { clients = ArrayList(this.clients) } for (client in clients) { if (client.equals(fromClient)) { continue } try { client.write(msg + "\r\n") } catch (e: Exception) { e.printStackTrace() } } } inner class Client internal constructor(private var socket: Socket?) : Runnable { private var output: Writer? = null var clientName: String? = null override fun run() { try { socket!!.sendBufferSize = 16384 socket!!.tcpNoDelay = true val input = BufferedReader(InputStreamReader(socket!!.getInputStream())) output = OutputStreamWriter(socket!!.getOutputStream()) write("Please enter your name: ") var line: String while (true) { line = input.readLine() if (null == line) { break } if (clientName == null) { line = line.trim { it <= ' ' } if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(onlineListCSV + "\r\n") broadcast(this, "+++ $clientName arrived +++") continue } if (line.equals("/quit", ignoreCase = true)) { return } broadcast(this, "$clientName> $line") } } catch (e: Exception) { e.printStackTrace() } finally { deRegisterClient(this) output = null try { socket!!.close() } catch (e: Exception) { e.printStackTrace() } socket = null } } @Throws(IOException::class) internal fun write(msg: String) { output!!.write(msg) output!!.flush() } internal fun equals(client: Client?): Boolean { return (client != null && clientName != null && client.clientName != null && clientName == client.clientName) } } companion object { @JvmStatic fun main(args: Array<String>) { var port = 4004 if (args.isNotEmpty()) { port = Integer.parseInt(args[0]) } ChatServer(port).run() } } }
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Can you help me rewrite this code in VB instead of Scala, keeping it the same logically?
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections class ChatServer private constructor(private val port: Int) : Runnable { private val clients = ArrayList<Client>() private val onlineListCSV: String @Synchronized get() { val sb = StringBuilder() sb.append(clients.size).append(" user(s) online: ") for (i in clients.indices) { sb.append(if (i > 0) ", " else "").append(clients[i].clientName) } return sb.toString() } override fun run() { try { val ss = ServerSocket(port) while (true) { val s = ss.accept() Thread(Client(s)).start() } } catch (e: Exception) { e.printStackTrace() } } @Synchronized private fun registerClient(client: Client): Boolean { for (otherClient in clients) { if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) { return false } } clients.add(client) return true } private fun deRegisterClient(client: Client) { var wasRegistered = false synchronized(this) { wasRegistered = clients.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private fun broadcast(fromClient: Client, msg: String) { var clients: List<Client> = Collections.emptyList() synchronized(this) { clients = ArrayList(this.clients) } for (client in clients) { if (client.equals(fromClient)) { continue } try { client.write(msg + "\r\n") } catch (e: Exception) { e.printStackTrace() } } } inner class Client internal constructor(private var socket: Socket?) : Runnable { private var output: Writer? = null var clientName: String? = null override fun run() { try { socket!!.sendBufferSize = 16384 socket!!.tcpNoDelay = true val input = BufferedReader(InputStreamReader(socket!!.getInputStream())) output = OutputStreamWriter(socket!!.getOutputStream()) write("Please enter your name: ") var line: String while (true) { line = input.readLine() if (null == line) { break } if (clientName == null) { line = line.trim { it <= ' ' } if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(onlineListCSV + "\r\n") broadcast(this, "+++ $clientName arrived +++") continue } if (line.equals("/quit", ignoreCase = true)) { return } broadcast(this, "$clientName> $line") } } catch (e: Exception) { e.printStackTrace() } finally { deRegisterClient(this) output = null try { socket!!.close() } catch (e: Exception) { e.printStackTrace() } socket = null } } @Throws(IOException::class) internal fun write(msg: String) { output!!.write(msg) output!!.flush() } internal fun equals(client: Client?): Boolean { return (client != null && clientName != null && client.clientName != null && clientName == client.clientName) } } companion object { @JvmStatic fun main(args: Array<String>) { var port = 4004 if (args.isNotEmpty()) { port = Integer.parseInt(args[0]) } ChatServer(port).run() } } }
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Translate the given Scala code snippet into Go without altering its behavior.
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections class ChatServer private constructor(private val port: Int) : Runnable { private val clients = ArrayList<Client>() private val onlineListCSV: String @Synchronized get() { val sb = StringBuilder() sb.append(clients.size).append(" user(s) online: ") for (i in clients.indices) { sb.append(if (i > 0) ", " else "").append(clients[i].clientName) } return sb.toString() } override fun run() { try { val ss = ServerSocket(port) while (true) { val s = ss.accept() Thread(Client(s)).start() } } catch (e: Exception) { e.printStackTrace() } } @Synchronized private fun registerClient(client: Client): Boolean { for (otherClient in clients) { if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) { return false } } clients.add(client) return true } private fun deRegisterClient(client: Client) { var wasRegistered = false synchronized(this) { wasRegistered = clients.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } } private fun broadcast(fromClient: Client, msg: String) { var clients: List<Client> = Collections.emptyList() synchronized(this) { clients = ArrayList(this.clients) } for (client in clients) { if (client.equals(fromClient)) { continue } try { client.write(msg + "\r\n") } catch (e: Exception) { e.printStackTrace() } } } inner class Client internal constructor(private var socket: Socket?) : Runnable { private var output: Writer? = null var clientName: String? = null override fun run() { try { socket!!.sendBufferSize = 16384 socket!!.tcpNoDelay = true val input = BufferedReader(InputStreamReader(socket!!.getInputStream())) output = OutputStreamWriter(socket!!.getOutputStream()) write("Please enter your name: ") var line: String while (true) { line = input.readLine() if (null == line) { break } if (clientName == null) { line = line.trim { it <= ' ' } if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(onlineListCSV + "\r\n") broadcast(this, "+++ $clientName arrived +++") continue } if (line.equals("/quit", ignoreCase = true)) { return } broadcast(this, "$clientName> $line") } } catch (e: Exception) { e.printStackTrace() } finally { deRegisterClient(this) output = null try { socket!!.close() } catch (e: Exception) { e.printStackTrace() } socket = null } } @Throws(IOException::class) internal fun write(msg: String) { output!!.write(msg) output!!.flush() } internal fun equals(client: Client?): Boolean { return (client != null && clientName != null && client.clientName != null && clientName == client.clientName) } } companion object { @JvmStatic fun main(args: Array<String>) { var port = 4004 if (args.isNotEmpty()) { port = Integer.parseInt(args[0]) } ChatServer(port).run() } } }
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Write the same code in C as shown below in Tcl.
package require Tcl 8.6 proc writeEveryoneElse {sender message} { dict for {who ch} $::cmap { if {$who ne $sender} { puts $ch $message } } } proc cgets {ch var} { upvar 1 $var v while {[gets $ch v] < 0} { if {[eof $ch] || [chan pending input $ch] > 256} { return false } yield } return true } proc chat {ch addr port} { fconfigure $ch -buffering none -blocking 0 -encoding utf-8 fileevent $ch readable [info coroutine] global cmap try { puts -nonewline $ch "Please enter your name: " if {![cgets $ch name]} { return } dict set cmap $name $ch writeEveryoneElse $name "+++ $name arrived +++" while {[cgets $ch line]} { writeEveryoneElse $name "$name> $line" } } finally { if {[info exists name]} { writeEveryoneElse $name "--- $name left ---" dict unset cmap $name } close $ch } } socket -server {coroutine c[incr count] chat} 4004 set ::cmap {}; vwait forever;
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
Translate the given Tcl code snippet into C# without altering its behavior.
package require Tcl 8.6 proc writeEveryoneElse {sender message} { dict for {who ch} $::cmap { if {$who ne $sender} { puts $ch $message } } } proc cgets {ch var} { upvar 1 $var v while {[gets $ch v] < 0} { if {[eof $ch] || [chan pending input $ch] > 256} { return false } yield } return true } proc chat {ch addr port} { fconfigure $ch -buffering none -blocking 0 -encoding utf-8 fileevent $ch readable [info coroutine] global cmap try { puts -nonewline $ch "Please enter your name: " if {![cgets $ch name]} { return } dict set cmap $name $ch writeEveryoneElse $name "+++ $name arrived +++" while {[cgets $ch line]} { writeEveryoneElse $name "$name> $line" } } finally { if {[info exists name]} { writeEveryoneElse $name "--- $name left ---" dict unset cmap $name } close $ch } } socket -server {coroutine c[incr count] chat} 4004 set ::cmap {}; vwait forever;
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
Change the programming language of this snippet from Tcl to Java without modifying what it does.
package require Tcl 8.6 proc writeEveryoneElse {sender message} { dict for {who ch} $::cmap { if {$who ne $sender} { puts $ch $message } } } proc cgets {ch var} { upvar 1 $var v while {[gets $ch v] < 0} { if {[eof $ch] || [chan pending input $ch] > 256} { return false } yield } return true } proc chat {ch addr port} { fconfigure $ch -buffering none -blocking 0 -encoding utf-8 fileevent $ch readable [info coroutine] global cmap try { puts -nonewline $ch "Please enter your name: " if {![cgets $ch name]} { return } dict set cmap $name $ch writeEveryoneElse $name "+++ $name arrived +++" while {[cgets $ch line]} { writeEveryoneElse $name "$name> $line" } } finally { if {[info exists name]} { writeEveryoneElse $name "--- $name left ---" dict unset cmap $name } close $ch } } socket -server {coroutine c[incr count] chat} 4004 set ::cmap {}; vwait forever;
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
Translate this program into Python but keep the logic exactly as in Tcl.
package require Tcl 8.6 proc writeEveryoneElse {sender message} { dict for {who ch} $::cmap { if {$who ne $sender} { puts $ch $message } } } proc cgets {ch var} { upvar 1 $var v while {[gets $ch v] < 0} { if {[eof $ch] || [chan pending input $ch] > 256} { return false } yield } return true } proc chat {ch addr port} { fconfigure $ch -buffering none -blocking 0 -encoding utf-8 fileevent $ch readable [info coroutine] global cmap try { puts -nonewline $ch "Please enter your name: " if {![cgets $ch name]} { return } dict set cmap $name $ch writeEveryoneElse $name "+++ $name arrived +++" while {[cgets $ch line]} { writeEveryoneElse $name "$name> $line" } } finally { if {[info exists name]} { writeEveryoneElse $name "--- $name left ---" dict unset cmap $name } close $ch } } socket -server {coroutine c[incr count] chat} 4004 set ::cmap {}; vwait forever;
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Port the following code from Tcl to VB with equivalent syntax and logic.
package require Tcl 8.6 proc writeEveryoneElse {sender message} { dict for {who ch} $::cmap { if {$who ne $sender} { puts $ch $message } } } proc cgets {ch var} { upvar 1 $var v while {[gets $ch v] < 0} { if {[eof $ch] || [chan pending input $ch] > 256} { return false } yield } return true } proc chat {ch addr port} { fconfigure $ch -buffering none -blocking 0 -encoding utf-8 fileevent $ch readable [info coroutine] global cmap try { puts -nonewline $ch "Please enter your name: " if {![cgets $ch name]} { return } dict set cmap $name $ch writeEveryoneElse $name "+++ $name arrived +++" while {[cgets $ch line]} { writeEveryoneElse $name "$name> $line" } } finally { if {[info exists name]} { writeEveryoneElse $name "--- $name left ---" dict unset cmap $name } close $ch } } socket -server {coroutine c[incr count] chat} 4004 set ::cmap {}; vwait forever;
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Produce a functionally identical Go code for the snippet given in Tcl.
package require Tcl 8.6 proc writeEveryoneElse {sender message} { dict for {who ch} $::cmap { if {$who ne $sender} { puts $ch $message } } } proc cgets {ch var} { upvar 1 $var v while {[gets $ch v] < 0} { if {[eof $ch] || [chan pending input $ch] > 256} { return false } yield } return true } proc chat {ch addr port} { fconfigure $ch -buffering none -blocking 0 -encoding utf-8 fileevent $ch readable [info coroutine] global cmap try { puts -nonewline $ch "Please enter your name: " if {![cgets $ch name]} { return } dict set cmap $name $ch writeEveryoneElse $name "+++ $name arrived +++" while {[cgets $ch line]} { writeEveryoneElse $name "$name> $line" } } finally { if {[info exists name]} { writeEveryoneElse $name "--- $name left ---" dict unset cmap $name } close $ch } } socket -server {coroutine c[incr count] chat} 4004 set ::cmap {}; vwait forever;
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
Generate a Rust translation of this C snippet without changing its computational steps.
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/select.h> #include <netinet/in.h> #include <netinet/ip.h> int tsocket; struct sockaddr_in tsockinfo; fd_set status, current; void ClientText(int handle, char *buf, int buf_len); struct client { char buffer[4096]; int pos; char name[32]; } *connections[FD_SETSIZE]; void AddConnection(int handle) { connections[handle] = malloc(sizeof(struct client)); connections[handle]->buffer[0] = '\0'; connections[handle]->pos = 0; connections[handle]->name[0] = '\0'; } void CloseConnection(int handle) { char buf[512]; int j; FD_CLR(handle, &status); if (connections[handle]->name[0]) { sprintf(buf, "* Disconnected: %s\r\n", connections[handle]->name); for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, buf, strlen(buf)) < 0) { CloseConnection(j); } } } } else { printf ("-- Connection %d disconnected\n", handle); } if (connections[handle]) { free(connections[handle]); } close(handle); } void strip(char *buf) { char *x; x = strchr(buf, '\n'); if (x) { *x='\0'; } x = strchr(buf, '\r'); if (x) { *x='\0'; } } int RelayText(int handle) { char *begin, *end; int ret = 0; begin = connections[handle]->buffer; if (connections[handle]->pos == 4000) { if (begin[3999] != '\n') begin[4000] = '\0'; else { begin[4000] = '\n'; begin[4001] = '\0'; } } else { begin[connections[handle]->pos] = '\0'; } end = strchr(begin, '\n'); while (end != NULL) { char output[8000]; output[0] = '\0'; if (!connections[handle]->name[0]) { strncpy(connections[handle]->name, begin, 31); connections[handle]->name[31] = '\0'; strip(connections[handle]->name); sprintf(output, "* Connected: %s\r\n", connections[handle]->name); ret = 1; } else { sprintf(output, "%s: %.*s\r\n", connections[handle]->name, end-begin, begin); ret = 1; } if (output[0]) { int j; for (j = 0; j < FD_SETSIZE; j++) { if (handle != j && j != tsocket && FD_ISSET(j, &status)) { if (write(j, output, strlen(output)) < 0) { CloseConnection(j); } } } } begin = end+1; end = strchr(begin, '\n'); } strcpy(connections[handle]->buffer, begin); connections[handle]->pos -= begin - connections[handle]->buffer; return ret; } void ClientText(int handle, char *buf, int buf_len) { int i, j; if (!connections[handle]) return; j = connections[handle]->pos; for (i = 0; i < buf_len; ++i, ++j) { connections[handle]->buffer[j] = buf[i]; if (j == 4000) { while (RelayText(handle)); j = connections[handle]->pos; } } connections[handle]->pos = j; while (RelayText(handle)); } int ChatLoop() { int i, j; FD_ZERO(&status); FD_SET(tsocket, &status); FD_SET(0, &status); while(1) { current = status; if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1) { perror("Select"); return 0; } for (i = 0; i < FD_SETSIZE; ++i) { if (FD_ISSET(i, &current)) { if (i == tsocket) { struct sockaddr_in cliinfo; socklen_t addrlen = sizeof(cliinfo); int handle; handle = accept(tsocket, &cliinfo, &addrlen); if (handle == -1) { perror ("Couldn't accept connection"); } else if (handle > FD_SETSIZE) { printf ("Unable to accept new connection.\n"); close(handle); } else { if (write(handle, "Enter name: ", 12) >= 0) { printf("-- New connection %d from %s:%hu\n", handle, inet_ntoa (cliinfo.sin_addr), ntohs(cliinfo.sin_port)); FD_SET(handle, &status); AddConnection(handle); } } } else { char buf[512]; int b; b = read(i, buf, 500); if (b <= 0) { CloseConnection(i); } else { ClientText(i, buf, b); } } } } } } int main (int argc, char*argv[]) { tsocket = socket(PF_INET, SOCK_STREAM, 0); tsockinfo.sin_family = AF_INET; tsockinfo.sin_port = htons(7070); if (argc > 1) { tsockinfo.sin_port = htons(atoi(argv[1])); } tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY); printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port)); if (bind(tsocket, &tsockinfo, sizeof(tsockinfo)) == -1) { perror("Couldn't bind socket"); return -1; } if (listen(tsocket, 10) == -1) { perror("Couldn't listen to port"); } ChatLoop(); return 0; }
use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread; type Username = String; fn broadcast_message( user: &str, clients: &mut HashMap<String, TcpStream>, message: &str, ) -> io::Result<()> { for (client, stream) in clients.iter_mut() { if client != user { writeln!(stream, "{}", message)?; } } Ok(()) } fn chat_loop(listener: &TcpListener) -> io::Result<()> { let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> = Arc::new(RwLock::new(HashMap::new())); println!("Accepting connections on {}", listener.local_addr()?.port()); for stream in listener.incoming() { match stream { Ok(stream) => { let client_clients = Arc::clone(&local_clients); thread::spawn(move || -> io::Result<()> { let mut reader = BufReader::new(stream.try_clone()?); let mut writer = stream; let mut name = String::new(); loop { write!(writer, "Please enter a username: ")?; reader.read_line(&mut name)?; name = name.trim().to_owned(); let clients = client_clients.read().unwrap(); if !clients.contains_key(&name) { writeln!(writer, "Welcome, {}!", &name)?; break; } writeln!(writer, "That username is taken.")?; name.clear(); } { let mut clients = client_clients.write().unwrap(); clients.insert(name.clone(), writer); broadcast_message( &name, &mut *clients, &format!("{} has joined the chat room.", &name), )?; } for line in reader.lines() { let mut clients = client_clients.write().unwrap(); broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?; } { let mut clients = client_clients.write().unwrap(); clients.remove(&name); broadcast_message( &name, &mut *clients, &format!("{} has left the chat room.", &name), )?; } Ok(()) }); } Err(e) => { println!("Connection failed: {}", e); } } } Ok(()) } fn main() { let listener = TcpListener::bind(("localhost", 7000)).unwrap(); chat_loop(&listener).unwrap(); }
Write a version of this C# function in Rust with identical behavior.
using System; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatServer { class State { private TcpClient client; private StringBuilder sb = new StringBuilder(); public string Name { get; } public State(string name, TcpClient client) { Name = name; this.client = client; } public void Add(byte b) { sb.Append((char)b); } public void Send(string text) { var bytes = Encoding.ASCII.GetBytes(string.Format("{0}\r\n", text)); client.GetStream().Write(bytes, 0, bytes.Length); } } class Program { static TcpListener listen; static Thread serverthread; static Dictionary<int, State> connections = new Dictionary<int, State>(); static void Main(string[] args) { listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 4004); serverthread = new Thread(new ThreadStart(DoListen)); serverthread.Start(); } private static void DoListen() { listen.Start(); Console.WriteLine("Server: Started server"); while (true) { Console.WriteLine("Server: Waiting..."); TcpClient client = listen.AcceptTcpClient(); Console.WriteLine("Server: Waited"); Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient)); clientThread.Start(client); } } private static void DoClient(object client) { TcpClient tClient = (TcpClient)client; Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId); byte[] bytes = Encoding.ASCII.GetBytes("Enter name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); string name = string.Empty; bool done = false; do { if (!tClient.Connected) { Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } name = Receive(tClient); done = true; if (done) { foreach (var cl in connections) { var state = cl.Value; if (state.Name == name) { bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: "); tClient.GetStream().Write(bytes, 0, bytes.Length); done = false; } } } } while (!done); connections.Add(Thread.CurrentThread.ManagedThreadId, new State(name, tClient)); Console.WriteLine("\tTotal connections: {0}", connections.Count); Broadcast(string.Format("+++ {0} arrived +++", name)); do { string text = Receive(tClient); if (text == "/quit") { Broadcast(string.Format("Connection from {0} closed.", name)); connections.Remove(Thread.CurrentThread.ManagedThreadId); Console.WriteLine("\tTotal connections: {0}", connections.Count); break; } if (!tClient.Connected) { break; } Broadcast(string.Format("{0}> {1}", name, text)); } while (true); Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId); tClient.Close(); Thread.CurrentThread.Abort(); } private static string Receive(TcpClient client) { StringBuilder sb = new StringBuilder(); do { if (client.Available > 0) { while (client.Available > 0) { char ch = (char)client.GetStream().ReadByte(); if (ch == '\r') { continue; } if (ch == '\n') { return sb.ToString(); } sb.Append(ch); } } Thread.Sleep(100); } while (true); } private static void Broadcast(string text) { Console.WriteLine(text); foreach (var oClient in connections) { if (oClient.Key != Thread.CurrentThread.ManagedThreadId) { State state = oClient.Value; state.Send(text); } } } } }
use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread; type Username = String; fn broadcast_message( user: &str, clients: &mut HashMap<String, TcpStream>, message: &str, ) -> io::Result<()> { for (client, stream) in clients.iter_mut() { if client != user { writeln!(stream, "{}", message)?; } } Ok(()) } fn chat_loop(listener: &TcpListener) -> io::Result<()> { let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> = Arc::new(RwLock::new(HashMap::new())); println!("Accepting connections on {}", listener.local_addr()?.port()); for stream in listener.incoming() { match stream { Ok(stream) => { let client_clients = Arc::clone(&local_clients); thread::spawn(move || -> io::Result<()> { let mut reader = BufReader::new(stream.try_clone()?); let mut writer = stream; let mut name = String::new(); loop { write!(writer, "Please enter a username: ")?; reader.read_line(&mut name)?; name = name.trim().to_owned(); let clients = client_clients.read().unwrap(); if !clients.contains_key(&name) { writeln!(writer, "Welcome, {}!", &name)?; break; } writeln!(writer, "That username is taken.")?; name.clear(); } { let mut clients = client_clients.write().unwrap(); clients.insert(name.clone(), writer); broadcast_message( &name, &mut *clients, &format!("{} has joined the chat room.", &name), )?; } for line in reader.lines() { let mut clients = client_clients.write().unwrap(); broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?; } { let mut clients = client_clients.write().unwrap(); clients.remove(&name); broadcast_message( &name, &mut *clients, &format!("{} has left the chat room.", &name), )?; } Ok(()) }); } Err(e) => { println!("Connection failed: {}", e); } } } Ok(()) } fn main() { let listener = TcpListener::bind(("localhost", 7000)).unwrap(); chat_loop(&listener).unwrap(); }
Write a version of this Go function in Rust with identical behavior.
package main import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" ) func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) } type Server struct { add chan *conn rem chan string msg chan string stop chan bool } func ListenAndServe(addr string) error { ln, err := net.Listen("tcp", addr) if err != nil { return err } log.Println("Listening for connections on", addr) defer ln.Close() s := &Server{ add: make(chan *conn), rem: make(chan string), msg: make(chan string), stop: make(chan bool), } go s.handleConns() for { rwc, err := ln.Accept() if err != nil { close(s.stop) return err } log.Println("New connection from", rwc.RemoteAddr()) go newConn(s, rwc).welcome() } } func (s *Server) handleConns() { conns := make(map[string]*conn) var dropConn func(string) writeAll := func(str string) { log.Printf("Broadcast: %q", str) for name, c := range conns { c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) _, err := c.Write([]byte(str)) if err != nil { log.Printf("Error writing to %q: %v", name, err) c.Close() delete(conns, name) defer dropConn(name) } } } dropConn = func(name string) { if c, ok := conns[name]; ok { log.Printf("Closing connection with %q from %v", name, c.RemoteAddr()) c.Close() delete(conns, name) } else { log.Printf("Dropped connection with %q", name) } str := fmt.Sprintf("--- %q disconnected ---\n", name) writeAll(str) } defer func() { writeAll("Server stopping!\n") for _, c := range conns { c.Close() } }() for { select { case c := <-s.add: if _, exists := conns[c.name]; exists { fmt.Fprintf(c, "Name %q is not available\n", c.name) go c.welcome() continue } str := fmt.Sprintf("+++ %q connected +++\n", c.name) writeAll(str) conns[c.name] = c go c.readloop() case str := <-s.msg: writeAll(str) case name := <-s.rem: dropConn(name) case <-s.stop: return } } } type conn struct { *bufio.Reader net.Conn server *Server name string } func newConn(s *Server, rwc net.Conn) *conn { return &conn{ Reader: bufio.NewReader(rwc), Conn: rwc, server: s, } } func (c *conn) welcome() { var err error for c.name = ""; c.name == ""; { fmt.Fprint(c, "Enter your name: ") c.name, err = c.ReadString('\n') if err != nil { log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) c.Close() return } c.name = strings.TrimSpace(c.name) } c.server.add <- c } func (c *conn) readloop() { for { msg, err := c.ReadString('\n') if err != nil { break } c.server.msg <- c.name + "> " + msg } c.server.rem <- c.name }
use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread; type Username = String; fn broadcast_message( user: &str, clients: &mut HashMap<String, TcpStream>, message: &str, ) -> io::Result<()> { for (client, stream) in clients.iter_mut() { if client != user { writeln!(stream, "{}", message)?; } } Ok(()) } fn chat_loop(listener: &TcpListener) -> io::Result<()> { let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> = Arc::new(RwLock::new(HashMap::new())); println!("Accepting connections on {}", listener.local_addr()?.port()); for stream in listener.incoming() { match stream { Ok(stream) => { let client_clients = Arc::clone(&local_clients); thread::spawn(move || -> io::Result<()> { let mut reader = BufReader::new(stream.try_clone()?); let mut writer = stream; let mut name = String::new(); loop { write!(writer, "Please enter a username: ")?; reader.read_line(&mut name)?; name = name.trim().to_owned(); let clients = client_clients.read().unwrap(); if !clients.contains_key(&name) { writeln!(writer, "Welcome, {}!", &name)?; break; } writeln!(writer, "That username is taken.")?; name.clear(); } { let mut clients = client_clients.write().unwrap(); clients.insert(name.clone(), writer); broadcast_message( &name, &mut *clients, &format!("{} has joined the chat room.", &name), )?; } for line in reader.lines() { let mut clients = client_clients.write().unwrap(); broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?; } { let mut clients = client_clients.write().unwrap(); clients.remove(&name); broadcast_message( &name, &mut *clients, &format!("{} has left the chat room.", &name), )?; } Ok(()) }); } Err(e) => { println!("Connection failed: {}", e); } } } Ok(()) } fn main() { let listener = TcpListener::bind(("localhost", 7000)).unwrap(); chat_loop(&listener).unwrap(); }
Write the same algorithm in Python as shown in this Rust implementation.
use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread; type Username = String; fn broadcast_message( user: &str, clients: &mut HashMap<String, TcpStream>, message: &str, ) -> io::Result<()> { for (client, stream) in clients.iter_mut() { if client != user { writeln!(stream, "{}", message)?; } } Ok(()) } fn chat_loop(listener: &TcpListener) -> io::Result<()> { let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> = Arc::new(RwLock::new(HashMap::new())); println!("Accepting connections on {}", listener.local_addr()?.port()); for stream in listener.incoming() { match stream { Ok(stream) => { let client_clients = Arc::clone(&local_clients); thread::spawn(move || -> io::Result<()> { let mut reader = BufReader::new(stream.try_clone()?); let mut writer = stream; let mut name = String::new(); loop { write!(writer, "Please enter a username: ")?; reader.read_line(&mut name)?; name = name.trim().to_owned(); let clients = client_clients.read().unwrap(); if !clients.contains_key(&name) { writeln!(writer, "Welcome, {}!", &name)?; break; } writeln!(writer, "That username is taken.")?; name.clear(); } { let mut clients = client_clients.write().unwrap(); clients.insert(name.clone(), writer); broadcast_message( &name, &mut *clients, &format!("{} has joined the chat room.", &name), )?; } for line in reader.lines() { let mut clients = client_clients.write().unwrap(); broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?; } { let mut clients = client_clients.write().unwrap(); clients.remove(&name); broadcast_message( &name, &mut *clients, &format!("{} has left the chat room.", &name), )?; } Ok(()) }); } Err(e) => { println!("Connection failed: {}", e); } } } Ok(()) } fn main() { let listener = TcpListener::bind(("localhost", 7000)).unwrap(); chat_loop(&listener).unwrap(); }
import socket import thread import time HOST = "" PORT = 4004 def accept(conn): def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ()) def broadcast(name, message): print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname()) users = {} while True: try: while True: try: conn, addr = server.accept() except socket.error: break accept(conn) for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
Rewrite the snippet below in Rust so it works the same as the original Java code.
import java.io.*; import java.net.*; import java.util.*; public class ChatServer implements Runnable { private int port = 0; private List<Client> clients = new ArrayList<Client>(); public ChatServer(int port) { this.port = port; } public void run() { try { ServerSocket ss = new ServerSocket(port); while (true) { Socket s = ss.accept(); new Thread(new Client(s)).start(); } } catch (Exception e) { e.printStackTrace(); } } private synchronized boolean registerClient(Client client) { for (Client otherClient : clients) if (otherClient.clientName.equalsIgnoreCase(client.clientName)) return false; clients.add(client); return true; } private void deregisterClient(Client client) { boolean wasRegistered = false; synchronized (this) { wasRegistered = clients.remove(client); } if (wasRegistered) broadcast(client, "--- " + client.clientName + " left ---"); } private synchronized String getOnlineListCSV() { StringBuilder sb = new StringBuilder(); sb.append(clients.size()).append(" user(s) online: "); for (int i = 0; i < clients.size(); i++) sb.append((i > 0) ? ", " : "").append(clients.get(i).clientName); return sb.toString(); } private void broadcast(Client fromClient, String msg) { List<Client> clients = null; synchronized (this) { clients = new ArrayList<Client>(this.clients); } for (Client client : clients) { if (client.equals(fromClient)) continue; try { client.write(msg + "\r\n"); } catch (Exception e) { } } } public class Client implements Runnable { private Socket socket = null; private Writer output = null; private String clientName = null; public Client(Socket socket) { this.socket = socket; } public void run() { try { socket.setSendBufferSize(16384); socket.setTcpNoDelay(true); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new OutputStreamWriter(socket.getOutputStream()); write("Please enter your name: "); String line = null; while ((line = input.readLine()) != null) { if (clientName == null) { line = line.trim(); if (line.isEmpty()) { write("A name is required. Please enter your name: "); continue; } clientName = line; if (!registerClient(this)) { clientName = null; write("Name already registered. Please enter your name: "); continue; } write(getOnlineListCSV() + "\r\n"); broadcast(this, "+++ " + clientName + " arrived +++"); continue; } if (line.equalsIgnoreCase("/quit")) return; broadcast(this, clientName + "> " + line); } } catch (Exception e) { } finally { deregisterClient(this); output = null; try { socket.close(); } catch (Exception e) { } socket = null; } } public void write(String msg) throws IOException { output.write(msg); output.flush(); } public boolean equals(Client client) { return (client != null) && (client instanceof Client) && (clientName != null) && (client.clientName != null) && clientName.equals(client.clientName); } } public static void main(String[] args) { int port = 4004; if (args.length > 0) port = Integer.parseInt(args[0]); new ChatServer(port).run(); } }
use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread; type Username = String; fn broadcast_message( user: &str, clients: &mut HashMap<String, TcpStream>, message: &str, ) -> io::Result<()> { for (client, stream) in clients.iter_mut() { if client != user { writeln!(stream, "{}", message)?; } } Ok(()) } fn chat_loop(listener: &TcpListener) -> io::Result<()> { let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> = Arc::new(RwLock::new(HashMap::new())); println!("Accepting connections on {}", listener.local_addr()?.port()); for stream in listener.incoming() { match stream { Ok(stream) => { let client_clients = Arc::clone(&local_clients); thread::spawn(move || -> io::Result<()> { let mut reader = BufReader::new(stream.try_clone()?); let mut writer = stream; let mut name = String::new(); loop { write!(writer, "Please enter a username: ")?; reader.read_line(&mut name)?; name = name.trim().to_owned(); let clients = client_clients.read().unwrap(); if !clients.contains_key(&name) { writeln!(writer, "Welcome, {}!", &name)?; break; } writeln!(writer, "That username is taken.")?; name.clear(); } { let mut clients = client_clients.write().unwrap(); clients.insert(name.clone(), writer); broadcast_message( &name, &mut *clients, &format!("{} has joined the chat room.", &name), )?; } for line in reader.lines() { let mut clients = client_clients.write().unwrap(); broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?; } { let mut clients = client_clients.write().unwrap(); clients.remove(&name); broadcast_message( &name, &mut *clients, &format!("{} has left the chat room.", &name), )?; } Ok(()) }); } Err(e) => { println!("Connection failed: {}", e); } } } Ok(()) } fn main() { let listener = TcpListener::bind(("localhost", 7000)).unwrap(); chat_loop(&listener).unwrap(); }
Generate a VB translation of this Rust snippet without changing its computational steps.
use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread; type Username = String; fn broadcast_message( user: &str, clients: &mut HashMap<String, TcpStream>, message: &str, ) -> io::Result<()> { for (client, stream) in clients.iter_mut() { if client != user { writeln!(stream, "{}", message)?; } } Ok(()) } fn chat_loop(listener: &TcpListener) -> io::Result<()> { let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> = Arc::new(RwLock::new(HashMap::new())); println!("Accepting connections on {}", listener.local_addr()?.port()); for stream in listener.incoming() { match stream { Ok(stream) => { let client_clients = Arc::clone(&local_clients); thread::spawn(move || -> io::Result<()> { let mut reader = BufReader::new(stream.try_clone()?); let mut writer = stream; let mut name = String::new(); loop { write!(writer, "Please enter a username: ")?; reader.read_line(&mut name)?; name = name.trim().to_owned(); let clients = client_clients.read().unwrap(); if !clients.contains_key(&name) { writeln!(writer, "Welcome, {}!", &name)?; break; } writeln!(writer, "That username is taken.")?; name.clear(); } { let mut clients = client_clients.write().unwrap(); clients.insert(name.clone(), writer); broadcast_message( &name, &mut *clients, &format!("{} has joined the chat room.", &name), )?; } for line in reader.lines() { let mut clients = client_clients.write().unwrap(); broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?; } { let mut clients = client_clients.write().unwrap(); clients.remove(&name); broadcast_message( &name, &mut *clients, &format!("{} has left the chat room.", &name), )?; } Ok(()) }); } Err(e) => { println!("Connection failed: {}", e); } } } Ok(()) } fn main() { let listener = TcpListener::bind(("localhost", 7000)).unwrap(); chat_loop(&listener).unwrap(); }
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") 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() 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 Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While 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
Convert this Ada block to C#, preserving its control flow and logic.
type Count is mod 2**64;
using System; using System.Drawing; class Program { static void Main() { Bitmap img1 = new Bitmap("Lenna50.jpg"); Bitmap img2 = new Bitmap("Lenna100.jpg"); if (img1.Size != img2.Size) { Console.Error.WriteLine("Images are of different sizes"); return; } float diff = 0; for (int y = 0; y < img1.Height; y++) { for (int x = 0; x < img1.Width; x++) { Color pixel1 = img1.GetPixel(x, y); Color pixel2 = img2.GetPixel(x, y); diff += Math.Abs(pixel1.R - pixel2.R); diff += Math.Abs(pixel1.G - pixel2.G); diff += Math.Abs(pixel1.B - pixel2.B); } } Console.WriteLine("diff: {0} %", 100 * (diff / 255) / (img1.Width * img1.Height * 3)); } }