Created
September 10, 2013 04:41
-
-
Save jgautsch/6505065 to your computer and use it in GitHub Desktop.
A simple UDP server that will receive some text, reverse it and send that as a response. Runs locally on port 1234 (127.0.0.1:1234)
This file contains hidden or 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' | |
require 'pp' | |
host = 'localhost' | |
port = 1234 | |
s = UDPSocket.new | |
s.bind(nil, port) | |
while 1 do | |
# Receive the packet | |
received = s.recvfrom(100) | |
puts "\t" | |
puts received.class | |
puts received.size | |
pp received | |
puts "\n" | |
# save the client host and port for sending response | |
client_host = received[1][2].to_s | |
client_port = received[1][1].to_s | |
# If the message sent was 'kill' then shut down the server | |
if received[0].strip.chomp == "kill" | |
puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" | |
puts "Shutting down server" | |
puts "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" | |
break | |
# Else, send the message back to the client, reversed | |
else | |
message = received[0].reverse | |
s.send(message, 0, client_host, client_port.to_i) | |
print "[server #{received[1][2]} - #{received[1][1]}]" | |
puts message | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment