Skip to content

Instantly share code, notes, and snippets.

@arashm
Created November 15, 2019 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arashm/1e88c92cb881ccdf4ef851471546ca0c to your computer and use it in GitHub Desktop.
Save arashm/1e88c92cb881ccdf4ef851471546ca0c to your computer and use it in GitHub Desktop.
Simple TCP/IP Server that can listen to multiple clients and send messages to all of them
# frozen_string_literal: true
require 'socket'
class Client
def initialize
@socket = TCPSocket.new('localhost', 2000)
end
def next_line
@socket.gets.chomp
rescue StandardError => e
@socket.close
raise e
end
def next_message
message = ''
while (line = next_line)
break if line.empty?
message += line
end
message
end
def keep_reading
while (message = next_message)
break if message.empty?
yield message
end
rescue StandardError => e
@socket.close
raise e
end
end
c = Client.new
c.keep_reading do |message|
puts message
end
# frozen_string_literal: true
require 'socket'
class Server
attr_reader :server
def initialize
@server = TCPServer.new 2000
@clients = []
listen_for_clients
end
def start
loop do
print 'Enter Message: '
stuff = gets
Thread.start(@clients) do |clients|
clients.each do |client|
client.puts "#{Time.now} - #{stuff.chomp}"
client.puts
client.flush
end
end.join
end
end
def listen_for_clients
Thread.new do
loop do
client_socket = @server.accept
@clients << client_socket
end
end
end
end
Server.new.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment