10
\$\begingroup\$

Write the shortest program that answers "Hello, World" to a network connection.

Conditions:

  • Program shall listen on port 12345
  • When a client connects, program shall write "Hello, World" to the newly opened socket connection and then close the connection
  • Program shall accept connections in a loop, i.e. handle any number of connects
  • Program does not need to handle parallel connections

Test:

prompt> telnet localhost 12345
Hello, World
prompt>
\$\endgroup\$
4
  • 6
    \$\begingroup\$ This is essentially a less interesting version of codegolf.stackexchange.com/questions/3988 \$\endgroup\$ Commented Apr 12, 2013 at 14:06
  • \$\begingroup\$ Does it have to close the connection after the Hello World! Or can it just hang? \$\endgroup\$ Commented Jan 19, 2017 at 17:32
  • \$\begingroup\$ @carusocomputing Second point. \$\endgroup\$ Commented Jan 19, 2017 at 19:41
  • \$\begingroup\$ I just think it's worth pointing out that this question was recently necro'd from 2013. That only means what it means, but I want to make sure people aren't missing this. \$\endgroup\$
    – H Walters
    Commented Jan 29, 2017 at 4:56

13 Answers 13

6
\$\begingroup\$

Bash (34)

nc -l 12345 <<<Hello,\ World;. $0
\$\endgroup\$
7
  • \$\begingroup\$ At least one and probably two characters of whitespace there are unnecessary. \$\endgroup\$ Commented Apr 12, 2013 at 14:49
  • \$\begingroup\$ If you mean nc -l12345<<<Hello, that doesn't work. nc needs the space between -l and 12345, and removing the space before <<< gets bad file descriptor from Bash. \$\endgroup\$
    – marinus
    Commented Apr 12, 2013 at 14:54
  • 1
    \$\begingroup\$ I suppose that nc is from BusyBox. The GNU netcat requires -p switch too. And with my bash 4.2.42 there is no such error if you remove the space before <<<. \$\endgroup\$
    – manatwork
    Commented Apr 12, 2013 at 15:20
  • 7
    \$\begingroup\$ this is the great thing with bash. you can never be sure that it works on an other machine. \$\endgroup\$ Commented Apr 12, 2013 at 16:26
  • 1
    \$\begingroup\$ @professorfish . is the same as source. So basically it sources itself. \$\endgroup\$
    – user344
    Commented Jun 25, 2014 at 20:54
3
\$\begingroup\$

Java, 268 Bytes

import java.io.*;import java.net.*;
class S{public static void main(String[]args)throws Exception{ServerSocket s=new ServerSocket(12345);while(1>0){Socket t=s.accept();PrintWriter u=new PrintWriter(t.getOutputStream());u.println("Hello World!");u.flush();t.close();}}}

Ungolfed:

import java.io.*;import java.net.*;
class S{
    public static void main(String[]args)throws Exception{
        ServerSocket s = new ServerSocket(12345);
        while(true) {
            Socket t = s.accept();
            PrintWriter u = new PrintWriter(t.getOutputStream()) ;
            u.println("Hello World!");
            u.flush();
            t.close();
        }
        s.close();
    }
}

enter image description here

\$\endgroup\$
8
  • \$\begingroup\$ Why the "?"? And yours ended up nearly exactly like mine. I guess there's only so many ways to do this in Java. \$\endgroup\$ Commented Jan 19, 2017 at 19:35
  • \$\begingroup\$ The ? was me contemplating whether or not to post it heh. Also, necrotic? \$\endgroup\$ Commented Jan 19, 2017 at 19:38
  • \$\begingroup\$ Ya, I bumped this from like 3 years ago. Seemed like a good challenge to put back out there. I guess they didn't say count units back then? And whoops, that was a swypo. Meant "nearly". \$\endgroup\$ Commented Jan 19, 2017 at 19:39
  • 2
    \$\begingroup\$ But for(;;) will! \$\endgroup\$
    – Jakob
    Commented Jan 19, 2017 at 20:06
  • 3
    \$\begingroup\$ -1 no freehand circle \$\endgroup\$ Commented Jan 22, 2017 at 1:05
2
\$\begingroup\$

Tcl, 78 chars

socket -server r 12345;proc r {s a b} {puts $s Hello,\ World;close $s};vwait r

the vwait r enters the event loop (not necessary with Tk) until the variable r is set. Usually you use the variable forever.
And the Hello,\ World is the same as {Hello, World} or "Hello, World"

\$\endgroup\$
2
\$\begingroup\$

C# 220

using System.Text;namespace System.Net.Sockets{class P{static void Main(){var s=new TcpListener(IPAddress.Any,12345);s.Start();while(true){using(var c=s.AcceptSocket()){c.Send(Encoding.UTF8.GetBytes("Hello World"));}}}}}

Ungolfed:

using System.Text;
namespace System.Net.Sockets
{
    class P
    {
        static void Main()
        {
            var s = new TcpListener(IPAddress.Any, 12345);
            s.Start();
            while (true)
            {
                using (var c = s.AcceptSocket())
                {
                    c.Send(Encoding.UTF8.GetBytes("Hello World"));
                }
            }
        }
    }
}

Pretty straightforward. I could have saved 14 characters by removing IPAddress.Any, but that would rely on using deprecated API ...

\$\endgroup\$
2
\$\begingroup\$

Groovy, 119 bytes

{s=new java.net.ServerSocket(12345);while(1){(u=(t=s.accept()).getOutputStream())<<"Hello, World";u.flush();t.close()}}

Port of my java answer.

\$\endgroup\$
3
  • \$\begingroup\$ Oh ya. Looks like a pretty simple syntax. \$\endgroup\$ Commented Jan 19, 2017 at 20:00
  • 1
    \$\begingroup\$ @Carcigenicate the best thing Groovy does is collections manipulations with additions like Python's map and lambda along with shorthand iteration like 1..100.each{println(it)} or vectorizing commands like 1..100.collect{it/2} results in 1 through 100 divided by 2 in a list. \$\endgroup\$ Commented Jan 19, 2017 at 21:25
  • \$\begingroup\$ Ya, that's pretty tiny. The Clojure equivalent to the first would be (mapv println (range 1 100)), or more correctly (doseq [n (range 1 100)] (println n)). Unfortunately, Clojure is far from a good golfing language. I just use it to practice. \$\endgroup\$ Commented Jan 19, 2017 at 21:32
2
\$\begingroup\$

Racket, 111 bytes

(do([l(tcp-listen 12345)])(#f)(let-values([(i o)(tcp-accept l)])(display"Hello, World"o)(close-output-port o)))

It always surprises me when the do form is shorter than explicit recursion. I'm not entirely certain if I'm required to close the input port. Please comment if you think I need to.

Ungolfed

(do ([l (tcp-listen 12345)]) (#f)
  (let-values ([(i o) (tcp-accept l)])
    (display "Hello, World" o)
    (close-output-port o)))
\$\endgroup\$
2
\$\begingroup\$

Clojure, 153 148 bytes

-5 byte using macros. See comments.

(let[s(java.net.ServerSocket. 12345)](while 1(with-open[c(.accept s)](doto(java.io.PrintWriter.(.getOutputStream c))(.write"Hello, World").flush))))

Full program that listens in a loop for incoming connections, and outputs as required. The Java-interop is killer here. I don't need the same libraries enough to justify an import though.

Pregolfed:

(defn server []
  (let [ss (java.net.ServerSocket. 12345)]
    (while 1
      ; Auto closes the client
      (with-open [c (.accept ss)]
         ; Passes the PrintWriter as the first argument to each function
         (doto (java.io.PrintWriter. (.getOutputStream c))
           (.write "Hello, World\n")
           ; Parentheses are optional if the function only takes 1 argument
           ; Ugly, but shorter
           .flush)))))
\$\endgroup\$
6
  • \$\begingroup\$ This is basically word-for-word what it'd be in Java but less verbose haha. Clojure is now on my list of things to check out. \$\endgroup\$ Commented Jan 19, 2017 at 19:37
  • \$\begingroup\$ @carusocomputing I can't recommend Clojure enough. Probably the language I'm going to write with for the next few years. It's just awesome. \$\endgroup\$ Commented Jan 19, 2017 at 19:45
  • \$\begingroup\$ Have you tried Groovy :)? It's my favorite for short-hand Java. \$\endgroup\$ Commented Jan 19, 2017 at 19:51
  • \$\begingroup\$ @carusocomputing I think I checked it out at some point, but I didn't like the aesthetics of it. Same reason a haven't learned Ruby yet; I just shudder when I look at it it. \$\endgroup\$ Commented Jan 19, 2017 at 19:52
  • 1
    \$\begingroup\$ @carusocomputing I think I was thinking of a different language. It actually looks like of nice. \$\endgroup\$ Commented Jan 19, 2017 at 19:54
2
\$\begingroup\$

Python, 103

import socket
s=socket.socket()
s.bind(('',12345))
s.listen(1)
s.accept()[0].sendall(b'Hello, World')
\$\endgroup\$
0
2
\$\begingroup\$

LiveScript (node.js), 73 bytes

(require(\net)createServer ->it.write 'Hello, World';it.end!)listen 12345
\$\endgroup\$
2
\$\begingroup\$

Go, 133 bytes

package main
import(n"net")
func main(){l,_:=n.Listen("tcp",":12345")
for{c,_:=l.Accept()
c.Write([]byte("Hello, World"))
c.Close()}}
\$\endgroup\$
1
\$\begingroup\$

Perl, 118 bytes

$s=new IO::Socket::INET LocalPort=>12345,Listen=>5,Reuse=>1;{$c=$s->accept;$c->send("Hello World");shutdown $c,1;redo}

Example:

$ perl -MIO::Socket -e '$s=new IO::Socket::INET LocalPort=>12345,Listen=>5,Reuse=>1;{$c=$s->accept;$c->send("Hello World");shutdown $c,1;redo}'

$ telnet localhost 12345
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello WorldConnection closed by foreign host.
$
\$\endgroup\$
1
\$\begingroup\$

Wolfram (102)

#[[2]] contains OutputStream of the incoming socket

<<SocketLink`;
CreateAsynchronousServer[CreateServerSocket@12345,(#[[2]]~Write~"Hello world";Close/@#)&]
\$\endgroup\$
1
  • \$\begingroup\$ Wolfram? Link to language page? \$\endgroup\$ Commented Feb 1, 2017 at 17:29
0
\$\begingroup\$

Ruby, 83 bytes

require'socket';s=TCPServer.new 12345;loop{t=s.accept;t<<"Hello, World\n";t.close}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.