socket.sf 1.2 KB

1234567891011121314151617181920212223242526272829
  1. #!/usr/bin/ruby
  2. # A very basic, low-level, web-server.
  3. var port = 8080;
  4. var protocol = Socket.getprotobyname( "tcp" );
  5. var sock = (Socket.open(Socket.PF_INET, Socket.SOCK_STREAM, protocol) || die "couldn't open a socket: #{$!}");
  6. # PF_INET to indicate that this socket will connect to the internet domain
  7. # SOCK_STREAM indicates a TCP stream, SOCK_DGRAM would indicate UDP communication
  8. sock.setsockopt(Socket.SOL_SOCKET, Socket.SO_REUSEADDR, 1) || die "couldn't set socket options: #{$!}";
  9. # SOL_SOCKET to indicate that we are setting an option on the socket instead of the protocol
  10. # mark the socket reusable
  11. sock.bind(Socket.sockaddr_in(port, Socket.INADDR_ANY)) || die "couldn't bind socket to port #{port}: #{$!}";
  12. # bind our socket to $port, allowing any IP to connect
  13. sock.listen(Socket.SOMAXCONN) || die "couldn't listen to port #{port}: #{$!}";
  14. # start listening for incoming connections
  15. while (var client = sock.accept) {
  16. client.print ("HTTP/1.1 200 OK\r\n" +
  17. "Content-Type: text/html; charset=UTF-8\r\n\r\n" +
  18. "<html><head><title>Goodbye, world!</title></head>" +
  19. "<body>Goodbye, world!</body></html>\r\n");
  20. client.close;
  21. }