This post is about using a port so that other applications will not use it in test scenarios. For instance, you have some tests that use a mock web service, and you require ranges of port numbers. So, the idea is to make Ruby block those ports temporarily for ourselves.
Ruby version
For reference, the ruby version we use for this post is 2.3 for Windows.
Of course, we require to install Ruby first, which, unfortunately, is not covered here.
Ruby Codes To Block Ports
Consider the following Ruby codes that make up a simple program. The application accepts a port and opens it up using TCPServer. Since the program will remain running because of the endless loop, the port will remain unavailable for use by other applications.
1 2 3 4 5 6 7 8 9 10 11 12 | require 'socket' # Get sockets from stdlib userPort = ARGV[0] server = TCPServer.open(userPort) # Socket to listen on port ARGV[0] puts "Using port " + userPort + ". Press Ctrl + C to exit" loop { # Servers run forever client = server.accept # Wait for a client to connect client.puts(Time.now.ctime) # Send the time to the client client.puts "This uses port to prevent other application from using the same port" client.puts "Closing the connection. Bye!" client.close # Disconnect from the client } |
We get the following output when we run the Ruby program with a random port number as its argument. Note that we can still terminate the program by pressing Ctrl + C.
What if we want Ruby to block more than one port at the same time? We could modify the codes to accept a list of port numbers to open up. Alternatively, we could hard-code those port numbers and run the program once using only one instance.
The codes still work in ruby 2.7.3p183.