Name

TCPServer — TCP/IP server socket class

Synopsis

TCPServer is a class for server-side TCP sockets. A TCPServer waits for client connection by the accept method, then returns a TCPSocket object connected to the client.

Required Library

require ’socket’

Example

require 'socket'

gs = TCPserver.open(0)
addr = gs.addr
addr.shift            # removes "AF_INET"
printf("server is on %s\n", addr.join(":"))

while true
   Thread.start(gs.accept) do |s|
     print(s, " is accepted\n")
     while s.gets
       s.write($_)
     end
     print(s, " is gone\n")
     s.close
   end
 end

Inherited Class

TCPSocket

Class Methods

TCPServer::new([host="localhost",] service)
TCPServer::open([host="localhost",] service)

Creates a server socket

Instance Method

s.accept

Waits for a connection and returns a new TCPSocket object once one is accepted

Get Ruby in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.