Hello World socket server

11

1

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>

Bernd

Posted 2013-04-12T13:06:41.883

Reputation: 211

Question was closed 2017-01-29T10:35:42.513

6

This is essentially a less interesting version of http://codegolf.stackexchange.com/questions/3988

– Peter Taylor – 2013-04-12T14:06:46.687

Does it have to close the connection after the Hello World! Or can it just hang? – Magic Octopus Urn – 2017-01-19T17:32:01.060

@carusocomputing Second point. – Carcigenicate – 2017-01-19T19:41:01.330

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. – H Walters – 2017-01-29T04:56:39.613

Answers

6

Bash (34)

nc -l 12345 <<<Hello,\ World;. $0

marinus

Posted 2013-04-12T13:06:41.883

Reputation: 30 224

At least one and probably two characters of whitespace there are unnecessary. – Peter Taylor – 2013-04-12T14:49:52.413

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. – marinus – 2013-04-12T14:54:42.657

1I 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 <<<. – manatwork – 2013-04-12T15:20:54.630

7this is the great thing with bash. you can never be sure that it works on an other machine. – Johannes Kuhn – 2013-04-12T16:26:51.907

I don't think this can handle any number of connects, as . $0 will quickly segfault your shell, due to a stackoverflow see here for more details.

– zeppelin – 2017-01-28T20:08:15.417

what does the . $0 at the end do? – None – 2014-04-21T07:51:14.367

1@professorfish . is the same as source. So basically it sources itself. – nyuszika7h – 2014-06-25T20:54:28.767

3

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

Magic Octopus Urn

Posted 2013-04-12T13:06:41.883

Reputation: 19 422

Why the "?"? And yours ended up nearly exactly like mine. I guess there's only so many ways to do this in Java. – Carcigenicate – 2017-01-19T19:35:29.727

The ? was me contemplating whether or not to post it heh. Also, necrotic? – Magic Octopus Urn – 2017-01-19T19:38:10.590

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". – Carcigenicate – 2017-01-19T19:39:37.890

Won't while(1) work? – Carcigenicate – 2017-01-19T19:42:29.750

@Carcigenicate maybe in Java 8 not Java 7 though. – Magic Octopus Urn – 2017-01-19T19:58:53.817

2But for(;;) will! – Jakob – 2017-01-19T20:06:35.270

3-1 no freehand circle – NoOneIsHere – 2017-01-22T01:05:59.863

@SeeOneRhino I have a tool called "SnagIt" haha. If it's on the computer and overrides my PrtSc button, might as well use it instead of paint! – Magic Octopus Urn – 2017-02-01T17:28:13.283

2

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)))))

Carcigenicate

Posted 2013-04-12T13:06:41.883

Reputation: 3 295

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. – Magic Octopus Urn – 2017-01-19T19:37:39.193

@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. – Carcigenicate – 2017-01-19T19:45:06.953

Have you tried Groovy :)? It's my favorite for short-hand Java. – Magic Octopus Urn – 2017-01-19T19:51:05.463

@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. – Carcigenicate – 2017-01-19T19:52:58.280

1@carusocomputing I think I was thinking of a different language. It actually looks like of nice. – Carcigenicate – 2017-01-19T19:54:48.447

http://codegolf.stackexchange.com/a/107414/59376 is my answer ported to Groovy, it's just shorthand Java :). – Magic Octopus Urn – 2017-01-19T19:57:45.890

2

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.

Magic Octopus Urn

Posted 2013-04-12T13:06:41.883

Reputation: 19 422

Oh ya. Looks like a pretty simple syntax. – Carcigenicate – 2017-01-19T20:00:25.503

1@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. – Magic Octopus Urn – 2017-01-19T21:25:46.793

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. – Carcigenicate – 2017-01-19T21:32:39.950

2

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)))

Winny

Posted 2013-04-12T13:06:41.883

Reputation: 1 120

2

Python, 103

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

Mehdi

Posted 2013-04-12T13:06:41.883

Reputation: 121

2

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"

Johannes Kuhn

Posted 2013-04-12T13:06:41.883

Reputation: 7 122

2

Go 133

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

Denys Séguret

Posted 2013-04-12T13:06:41.883

Reputation: 780

2

LiveScript (node.js), 73 bytes

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

nyuszika7h

Posted 2013-04-12T13:06:41.883

Reputation: 1 624

2

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 ...

Num Lock

Posted 2013-04-12T13:06:41.883

Reputation: 211

1

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.
$

steve

Posted 2013-04-12T13:06:41.883

Reputation: 2 276

1

Wolfram (102)

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

<<SocketLink`;
CreateAsynchronousServer[CreateServerSocket@12345,(#[[2]]~Write~"Hello world";Close/@#)&]

swish

Posted 2013-04-12T13:06:41.883

Reputation: 7 484

Wolfram? Link to language page? – Magic Octopus Urn – 2017-02-01T17:29:07.340

0

Ruby, 83 bytes

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

undur_gongor

Posted 2013-04-12T13:06:41.883

Reputation: 191