WeixiangYan/CodeTransOcean huggingface dataset:
Task: Echo server



C#: using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static TcpListener listen;
        static Thread serverthread;

        static void Main(string[] args)
        {
            listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 12321);
            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);
            do
            {
                if (!tClient.Connected)
                { 
                    tClient.Close();
                    Thread.CurrentThread.Abort();       
                }

                if (tClient.Available > 0)
                {
                    
                    byte pByte = (byte)tClient.GetStream().ReadByte();
                    Console.WriteLine("Client (Thread: {0}): Data {1}", Thread.CurrentThread.ManagedThreadId, pByte);
                    tClient.GetStream().WriteByte(pByte);
                }

                
                Thread.Sleep(100);
            } while (true);
        }
    }
}





Python: import SocketServer

HOST = "localhost"
PORT = 12321




class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    
    pass

class EchoRequestHandler(SocketServer.StreamRequestHandler):
    
    def handle(self):
        print "connection from %s" % self.client_address[0]
        while True:
            line = self.rfile.readline()
            if not line: break
            print "%s wrote: %s" % (self.client_address[0], line.rstrip())
            self.wfile.write(line)
        print "%s disconnected" % self.client_address[0]



server = EchoServer((HOST, PORT), EchoRequestHandler)



print "server listening on %s:%s" % server.server_address
server.serve_forever()
Task: Echo server



C#: using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static TcpListener listen;
        static Thread serverthread;

        static void Main(string[] args)
        {
            listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 12321);
            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);
            do
            {
                if (!tClient.Connected)
                { 
                    tClient.Close();
                    Thread.CurrentThread.Abort();       
                }

                if (tClient.Available > 0)
                {
                    
                    byte pByte = (byte)tClient.GetStream().ReadByte();
                    Console.WriteLine("Client (Thread: {0}): Data {1}", Thread.CurrentThread.ManagedThreadId, pByte);
                    tClient.GetStream().WriteByte(pByte);
                }

                
                Thread.Sleep(100);
            } while (true);
        }
    }
}






VB: Class EchoSocket
Inherits TCPSocket
  Sub DataAvailable()
    If Instr(Me.LookAhead, EndofLine.Windows) > 0 Then
      Dim data As String = Me.ReadAll
      Dim lines() As String = Split(data, EndofLine.Windows)
      For i As Integer = 0 To Ubound(lines)
        Me.Write(lines(i) + EndOfLine.Windows)
        Print(lines(i))
      Next
    End If
  End Sub
End Class

Class EchoServer
Inherits ServerSocket
  Function AddSocket() As TCPSocket
    Return New EchoSocket
  End Function
End Class

Class App
Inherits ConsoleApplication
  Function Run(args() As String) As Integer
    Listener = New EchoServer
    Listener.Port = 12321
    Listener.Listen()
    While True
      DoEvents() 
    Wend
  End Function
  Private Listener As EchoServer
End Class
Task: Echo server




Go: package main

import (
	"fmt"
	"net"
	"bufio"
)

func echo(s net.Conn, i int) {
	defer s.Close();

	fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr())
	b := bufio.NewReader(s)
	for {
		line, e := b.ReadBytes('\n')
		if e != nil {
			break
		}
		s.Write(line)
	}
	fmt.Printf("%d: closed\n", i)
}

func main() {
	l, e := net.Listen("tcp", ":12321")
	for i := 0; e == nil; i++ {
		var s net.Conn
		s, e = l.Accept()
		go echo(s, i)
	}
}


Java: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class EchoServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket listener = new ServerSocket(12321)) {
            while (true) {
                Socket conn = listener.accept();
                Thread clientThread = new Thread(() -> handleClient(conn));
                clientThread.start();
            }
        }
    }

    private static void handleClient(Socket connArg) {
        Charset utf8 = StandardCharsets.UTF_8;

        try (Socket conn = connArg) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), utf8));

            PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(conn.getOutputStream(), utf8),
                    true);

            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Task: Echo server





Java: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class EchoServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket listener = new ServerSocket(12321)) {
            while (true) {
                Socket conn = listener.accept();
                Thread clientThread = new Thread(() -> handleClient(conn));
                clientThread.start();
            }
        }
    }

    private static void handleClient(Socket connArg) {
        Charset utf8 = StandardCharsets.UTF_8;

        try (Socket conn = connArg) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), utf8));

            PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(conn.getOutputStream(), utf8),
                    true);

            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



Python: import SocketServer

HOST = "localhost"
PORT = 12321




class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    
    pass

class EchoRequestHandler(SocketServer.StreamRequestHandler):
    
    def handle(self):
        print "connection from %s" % self.client_address[0]
        while True:
            line = self.rfile.readline()
            if not line: break
            print "%s wrote: %s" % (self.client_address[0], line.rstrip())
            self.wfile.write(line)
        print "%s disconnected" % self.client_address[0]



server = EchoServer((HOST, PORT), EchoRequestHandler)



print "server listening on %s:%s" % server.server_address
server.serve_forever()
Task: Echo server




Go: package main

import (
	"fmt"
	"net"
	"bufio"
)

func echo(s net.Conn, i int) {
	defer s.Close();

	fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr())
	b := bufio.NewReader(s)
	for {
		line, e := b.ReadBytes('\n')
		if e != nil {
			break
		}
		s.Write(line)
	}
	fmt.Printf("%d: closed\n", i)
}

func main() {
	l, e := net.Listen("tcp", ":12321")
	for i := 0; e == nil; i++ {
		var s net.Conn
		s, e = l.Accept()
		go echo(s, i)
	}
}




Python: import SocketServer

HOST = "localhost"
PORT = 12321




class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    
    pass

class EchoRequestHandler(SocketServer.StreamRequestHandler):
    
    def handle(self):
        print "connection from %s" % self.client_address[0]
        while True:
            line = self.rfile.readline()
            if not line: break
            print "%s wrote: %s" % (self.client_address[0], line.rstrip())
            self.wfile.write(line)
        print "%s disconnected" % self.client_address[0]



server = EchoServer((HOST, PORT), EchoRequestHandler)



print "server listening on %s:%s" % server.server_address
server.serve_forever()
Task: Echo server




Go: package main

import (
	"fmt"
	"net"
	"bufio"
)

func echo(s net.Conn, i int) {
	defer s.Close();

	fmt.Printf("%d: %v <-> %v\n", i, s.LocalAddr(), s.RemoteAddr())
	b := bufio.NewReader(s)
	for {
		line, e := b.ReadBytes('\n')
		if e != nil {
			break
		}
		s.Write(line)
	}
	fmt.Printf("%d: closed\n", i)
}

func main() {
	l, e := net.Listen("tcp", ":12321")
	for i := 0; e == nil; i++ {
		var s net.Conn
		s, e = l.Accept()
		go echo(s, i)
	}
}





VB: Class EchoSocket
Inherits TCPSocket
  Sub DataAvailable()
    If Instr(Me.LookAhead, EndofLine.Windows) > 0 Then
      Dim data As String = Me.ReadAll
      Dim lines() As String = Split(data, EndofLine.Windows)
      For i As Integer = 0 To Ubound(lines)
        Me.Write(lines(i) + EndOfLine.Windows)
        Print(lines(i))
      Next
    End If
  End Sub
End Class

Class EchoServer
Inherits ServerSocket
  Function AddSocket() As TCPSocket
    Return New EchoSocket
  End Function
End Class

Class App
Inherits ConsoleApplication
  Function Run(args() As String) As Integer
    Listener = New EchoServer
    Listener.Port = 12321
    Listener.Listen()
    While True
      DoEvents() 
    Wend
  End Function
  Private Listener As EchoServer
End Class
Task: Echo server







Python: import SocketServer

HOST = "localhost"
PORT = 12321




class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    
    pass

class EchoRequestHandler(SocketServer.StreamRequestHandler):
    
    def handle(self):
        print "connection from %s" % self.client_address[0]
        while True:
            line = self.rfile.readline()
            if not line: break
            print "%s wrote: %s" % (self.client_address[0], line.rstrip())
            self.wfile.write(line)
        print "%s disconnected" % self.client_address[0]



server = EchoServer((HOST, PORT), EchoRequestHandler)



print "server listening on %s:%s" % server.server_address
server.serve_forever()


VB: Class EchoSocket
Inherits TCPSocket
  Sub DataAvailable()
    If Instr(Me.LookAhead, EndofLine.Windows) > 0 Then
      Dim data As String = Me.ReadAll
      Dim lines() As String = Split(data, EndofLine.Windows)
      For i As Integer = 0 To Ubound(lines)
        Me.Write(lines(i) + EndOfLine.Windows)
        Print(lines(i))
      Next
    End If
  End Sub
End Class

Class EchoServer
Inherits ServerSocket
  Function AddSocket() As TCPSocket
    Return New EchoSocket
  End Function
End Class

Class App
Inherits ConsoleApplication
  Function Run(args() As String) As Integer
    Listener = New EchoServer
    Listener.Port = 12321
    Listener.Listen()
    While True
      DoEvents() 
    Wend
  End Function
  Private Listener As EchoServer
End Class
Task: Echo server

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#define MAX_ENQUEUED 20
#define BUF_LEN 256
#define PORT_STR "12321"





void wait_for_zombie(int s)
{
    while(waitpid(-1, NULL, WNOHANG) > 0) ;
}





void echo_lines(int csock)
{
    char buf[BUF_LEN];
    int r;

    while( (r = read(csock, buf, BUF_LEN)) > 0 ) {
        (void)write(csock, buf, r);
    }
    exit(EXIT_SUCCESS);
}





void take_connections_forever(int ssock)
{
    for(;;) {
        struct sockaddr addr;
        socklen_t addr_size = sizeof(addr);
        int csock;

        
        csock = accept(ssock, &addr, &addr_size);

        
        if ( csock == -1 ) {
            perror("accept");
        } else if ( fork() == 0 ) {
            close(ssock);
            echo_lines(csock);
        } else {
            close(csock);
        }
    }
}





int main()
{
    struct addrinfo hints, *res;
    struct sigaction sa;
    int sock;

    
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) {
        perror("getaddrinfo");
        exit(EXIT_FAILURE);
    }

    
    if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    
    sa.sa_handler = wait_for_zombie;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if ( sigaction(SIGCHLD, &sa, NULL) == -1 ) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    
    if ( bind(sock, res->ai_addr, res->ai_addrlen) != 0 ) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(res);

    
    if ( listen(sock, MAX_ENQUEUED) != 0 ) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    
    take_connections_forever(sock);
    return EXIT_SUCCESS;
}







Python: import SocketServer

HOST = "localhost"
PORT = 12321




class EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    
    pass

class EchoRequestHandler(SocketServer.StreamRequestHandler):
    
    def handle(self):
        print "connection from %s" % self.client_address[0]
        while True:
            line = self.rfile.readline()
            if not line: break
            print "%s wrote: %s" % (self.client_address[0], line.rstrip())
            self.wfile.write(line)
        print "%s disconnected" % self.client_address[0]



server = EchoServer((HOST, PORT), EchoRequestHandler)



print "server listening on %s:%s" % server.server_address
server.serve_forever()
Task: Echo server



C#: using System.Net.Sockets;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static TcpListener listen;
        static Thread serverthread;

        static void Main(string[] args)
        {
            listen = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 12321);
            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);
            do
            {
                if (!tClient.Connected)
                { 
                    tClient.Close();
                    Thread.CurrentThread.Abort();       
                }

                if (tClient.Available > 0)
                {
                    
                    byte pByte = (byte)tClient.GetStream().ReadByte();
                    Console.WriteLine("Client (Thread: {0}): Data {1}", Thread.CurrentThread.ManagedThreadId, pByte);
                    tClient.GetStream().WriteByte(pByte);
                }

                
                Thread.Sleep(100);
            } while (true);
        }
    }
}



Java: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class EchoServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket listener = new ServerSocket(12321)) {
            while (true) {
                Socket conn = listener.accept();
                Thread clientThread = new Thread(() -> handleClient(conn));
                clientThread.start();
            }
        }
    }

    private static void handleClient(Socket connArg) {
        Charset utf8 = StandardCharsets.UTF_8;

        try (Socket conn = connArg) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), utf8));

            PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(conn.getOutputStream(), utf8),
                    true);

            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Task: Echo server





Java: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class EchoServer {

    public static void main(String[] args) throws IOException {
        try (ServerSocket listener = new ServerSocket(12321)) {
            while (true) {
                Socket conn = listener.accept();
                Thread clientThread = new Thread(() -> handleClient(conn));
                clientThread.start();
            }
        }
    }

    private static void handleClient(Socket connArg) {
        Charset utf8 = StandardCharsets.UTF_8;

        try (Socket conn = connArg) {
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), utf8));

            PrintWriter out = new PrintWriter(
                    new OutputStreamWriter(conn.getOutputStream(), utf8),
                    true);

            String line;
            while ((line = in.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




VB: Class EchoSocket
Inherits TCPSocket
  Sub DataAvailable()
    If Instr(Me.LookAhead, EndofLine.Windows) > 0 Then
      Dim data As String = Me.ReadAll
      Dim lines() As String = Split(data, EndofLine.Windows)
      For i As Integer = 0 To Ubound(lines)
        Me.Write(lines(i) + EndOfLine.Windows)
        Print(lines(i))
      Next
    End If
  End Sub
End Class

Class EchoServer
Inherits ServerSocket
  Function AddSocket() As TCPSocket
    Return New EchoSocket
  End Function
End Class

Class App
Inherits ConsoleApplication
  Function Run(args() As String) As Integer
    Listener = New EchoServer
    Listener.Port = 12321
    Listener.Listen()
    While True
      DoEvents() 
    Wend
  End Function
  Private Listener As EchoServer
End Class
Task: Echo server

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>

#define MAX_ENQUEUED 20
#define BUF_LEN 256
#define PORT_STR "12321"





void wait_for_zombie(int s)
{
    while(waitpid(-1, NULL, WNOHANG) > 0) ;
}





void echo_lines(int csock)
{
    char buf[BUF_LEN];
    int r;

    while( (r = read(csock, buf, BUF_LEN)) > 0 ) {
        (void)write(csock, buf, r);
    }
    exit(EXIT_SUCCESS);
}





void take_connections_forever(int ssock)
{
    for(;;) {
        struct sockaddr addr;
        socklen_t addr_size = sizeof(addr);
        int csock;

        
        csock = accept(ssock, &addr, &addr_size);

        
        if ( csock == -1 ) {
            perror("accept");
        } else if ( fork() == 0 ) {
            close(ssock);
            echo_lines(csock);
        } else {
            close(csock);
        }
    }
}





int main()
{
    struct addrinfo hints, *res;
    struct sigaction sa;
    int sock;

    
    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) {
        perror("getaddrinfo");
        exit(EXIT_FAILURE);
    }

    
    if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) {
        perror("socket");
        exit(EXIT_FAILURE);
    }

    
    sa.sa_handler = wait_for_zombie;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if ( sigaction(SIGCHLD, &sa, NULL) == -1 ) {
        perror("sigaction");
        exit(EXIT_FAILURE);
    }

    
    if ( bind(sock, res->ai_addr, res->ai_addrlen) != 0 ) {
        perror("bind");
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(res);

    
    if ( listen(sock, MAX_ENQUEUED) != 0 ) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    
    take_connections_forever(sock);
    return EXIT_SUCCESS;
}






PHP: $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket, '127.0.0.1', 12321);
socket_listen($socket);

$client_count = 0;
while (true){
  if (($client = socket_accept($socket)) === false) continue;
  $client_count++;

  $client_name = 'Unknown';
  socket_getpeername($client, $client_name);
  echo "Client {$client_count} ({$client_name}) connected\n";
  $pid = pcntl_fork();
  if($pid == -1) die('Could not fork');
  if($pid){
    pcntl_waitpid(-1, $status, WNOHANG);
    continue;
  }

  while(true){
    if($input = socket_read($client, 1024)){
      socket_write($client, $input);
    } else {
      socket_shutdown($client);
      socket_close($client);
      echo "Client {$client_count} ({$client_name}) disconnected\n";
      exit();
    }
  }
}