Skip to content

Instantly share code, notes, and snippets.

@fabioxgn
Created June 1, 2021 00:40
Show Gist options
  • Save fabioxgn/eb98500425b504d994af8a7e5773ad53 to your computer and use it in GitHub Desktop.
Save fabioxgn/eb98500425b504d994af8a7e5773ad53 to your computer and use it in GitHub Desktop.
Ruby TCP example
require "socket"
socket = TCPSocket.open("localhost", 6666)
loop do
input = gets.chomp #Ask client for command
socket.puts input # Send command to server
line = socket.gets #Get server response
puts line
break if input=="exit" #If client types EXIT terminate connection
end
socket.close
server.rb
require "socket"
server = TCPServer.new 6666
loop do
Thread.start(server.accept) do |session| #accept client
sock_domain, remote_port, remote_hostname, remote_ip = session.peeraddr
puts "Incoming connection from #{remote_ip}"
while (line = session.gets) do #get client command
puts line
session.puts "ok"
break if line == 'exit'
end
puts "bye!"
session.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment