Created
June 1, 2021 00:40
-
-
Save fabioxgn/eb98500425b504d994af8a7e5773ad53 to your computer and use it in GitHub Desktop.
Ruby TCP example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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