Ruby TCPSocket communication - ruby

I am learning TCPSocket and have a simple server written:
require 'socket'
server = TCPServer.open(2000)
loop {
client = server.accept
p client.gets
client.print("bar")
client.close
}
and simple client written:
require 'socket'
hostname = 'localhost'
port = 2000
socket = TCPSocket.open(hostname, port)
socket.print("foo")
p socket.gets
When I run these in separate terminals with either the server or client communicating one way (i.e. one "prints" and the other "gets") I get the expected string on the other side. When I run these as written, with the client first "print"-ing a message to the server and then the server "gets"ing it to then "print" a string to the client, it just hangs. What is causing this issue?

Your program does following:
The connection is established between client and server.
Client side
Calls print("foo") - exactly 3 bytes are transmitted to the server.
Calls gets - waits for data from server but server never send any.
Server side
Calls gets - The ruby function gets parse stream data and it always return the whole line. But the server received only "foo" and the it has no idea whether it is whole line or not. So it is waiting forever for new line character which client never send.

Related

How to get other computer to connect to my localhost server?

I recently started learning Ruby Sockets and decided to research the topic. I came across the ruby-doc which had some example code that ran smoothly:
This is the example code for the server:
require 'socket'
server = TCPServer.new 2000 # Server bound to port 2000
loop do
client = server.accept # Wait for a client to connect
client.puts "Hello !"
client.puts "Time is #{Time.now}"
client.close
end
And the example code for the client:
require 'socket'
s = TCPSocket.new 'localhost', 2000
while line = s.gets # Read lines from socket
puts line # and print them
end
s.close # close socket when done
So this ran well but I was wondering how I would get the client to connect if it is running from a different computer. So I attempted to replace the "'localhost'" in the client code with my public IP address courtesy of whatismyip.com, however, when I tried running the new client code on a different computer I merely got a timeout error. I even attempted running the new client code on the same machine running the server but still I got a timeout error.
Does anyone know how I can get this to work properly?
Any help would be much appreciated!
Greg Hewgill helped me figure this out:
My first problem was that I was using the wrong address. Greg suggested I check my actual address through the cmd command "ipconfig". The command gave me the actual address that the server was being hosted on. Through this I changed the "'localhost'" in the client code and changed it to the actual IP address. Upon running, I received an error that stated that the server had actively refused the connection. This was fixed by also changing the 'localhost' in the server code to the IP address of the server's machine.
Thank you Greg for the help!

Keeping TCPSocket open: server or client's responsibility?

I have been reading examples online about Ruby's TCPSocket and TCPServer, but I still don't know and can't find what's the best practice for this. If you have a running TCPServer, and you want to keep the socket open across multiple connections/clients, who should be responsible in keeping them open, the server or the clients?
Let's say that you have a TCPServer running:
server = TCPServer.new(8000)
loop do
client = server.accept
while line = client.gets
# process data from client
end
client.puts "Response from server"
client.close # should server close the socket?
end
And Client:
socket = TCPSocket.new 'localhost', 8000
while line = socket.gets
# process data from server
end
socket.close # should client close the socket here?
All of the examples I have seen have the socket.close at the end, which I would assume is not what I want as that would close the connection. Server and clients should maintain open connection as they will need to send data back and forth.
PS: I'm pretty a noob on networking, so just kindly let me know if my question sounds completely dumb.
The server is usually responsible for keeping the connections open because the client (being the one connecting to the server) can break the connection at anytime.
Servers are usually in charge of everything that the client doesn't care about. A video game doesn't really care about the connection to the server as long as it's there. It just wants its data so it can keep running.

Add SSL to a connection

How do you secure a socket with SSL in Ruby when you need to communicate over plaintext first?
I can't use OpenSSL::SSL::SSLServer because it's the client's responsibility to request an SSL connection first
To put a long story short, I am attempting to implement RFC3207, where the client sends the keyword "STARTTLS", and then an SSL connection is created.
My question is "How do I create the SSL connection after the server has sent '220 OK'?"
I know I can use OpenSSL::SSL::SSLSocket on the client-side, but I have no idea what to do on the server-side
If you know how to do this in a language other than Ruby, just post the code and I'll translate it, I've been working on this for about 8 hours and I need everything I can get
I have asked in #ruby-lang, but with no avail, and I have tried wrapping Socket objects in SSLSockets on the server and client at the same time, but that isn't working either
In short, I'm very stuck, I need all the help I can get
I created this gist to illustrate how to set up a minimal TLS server. You may want to leave out lines 62-67, that was to illustrate a new feature on trunk.
But other than that, it's a fully working TLS server, you may build on it to add further functionality.
You may also want to change the server certificate's CN from "localhost" to a real domain if you want to use it seriously :)
You may notice that the largest part of the work is actually setting up the PKI aspects correctly. The core server part is this:
ctx = OpenSSL::SSL::SSLContext.new
ctx.cert = ... # the server certificate
ctx.key = ... # the key associated with this certificate
ctx.ssl_version = :SSLv23
tcps = TCPServer.new('127.0.0.1', 8443)
ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx)
ssls.start_immediately = true
begin
loop do
ssl = ssls.accept
puts "Connected"
begin
while line = ssl.gets
puts "Client says: #{line}"
ssl.write(line) # simple echo, do something more useful here
end
ensure
ssl.close
end
end
ensure
tcps.close if tcps
end
You have to set the SSLServer's start_immediately field to false in order to start the SSL server in plain text mode. At any point (ie. when you receive the STARTTLS command from the client), you can call the SSLSocket's accept method to initiate SSL/TLS handshake. The client will of course have to agree to the protocol :)
Here is a sample server I wrote to test this:
#!/usr/bin/ruby
require 'socket';
require 'openssl';
certfile = 'mycert.pem';
port = 9002;
server = TCPServer.new( port );
# Establish an SSL context
sslContext = OpenSSL::SSL::SSLContext.new
sslContext.cert = OpenSSL::X509::Certificate.new( File.open( certfile ) );
sslContext.key = OpenSSL::PKey::RSA.new( File.open( certfile ) );
# Create SSL server
sslServer = OpenSSL::SSL::SSLServer.new( server, sslContext );
# Don't expect an immidate SSL handshake upon connection.
sslServer.start_immediately = false;
sslSocket = sslServer.accept;
sslSocket.puts( "Toast.." );
# Server loop
while line = sslSocket.gets
line.chomp!;
if "STARTTLS" == line
# Starting TLS
sslSocket.accept;
end
sslSocket.puts( "Got '#{line}'" );
end
sslSocket.close;
I'm sure the original poster knows how to test STARTTLS, but the rest of us might need this reminder. Actaually I'm normally using the utils from the GNUTLS package (gnutls-bin in debian/ubuntu) to test starttls, because it allows me to start the handshake whenever I want to:
$ gnutls-cli --starttls --port 9002 --insecure localhost
This connects in plain text TCP socket mode. Type some lines and get them echoed. This traffic is unencrypted. If you send STARTTLS, the sslSocket.accept is called, and the server waits for SSL handshake. Press ctrl-d (EOF) to start handshake from the gnutls client, and watch it establish an encrypted SSL connection. Subsequent lines will be echoed as well, but the traffic is now encrypted.
I have made some headway on this, saved for future use:
Yes, you should use OpenSSL::SSL::SSLSocket on both ends
On the server side, you must create an OpenSSL::SSL::SSLContext object, passing in a symbol with the protocol you wish to use and "_server" appended to the end, see OpenSSL::SSL::SSLContext::METHODS for what I mean, in short use ":TLSv1_server" for RFC3207 don't even need to do that, on the server side create the context with certs and then call #accept on the socket to wait for client transfer
Pass in SSL certificates to the ctx object
Edit as you please

lua socket client

I am trying to make a simple lua socket client for the Socket Server example, from the Lua Socket page.
The server part works though, I tried it with telnet.
But the client part isn't working.
local host, port = "127.0.0.1", 100
local socket = require("socket")
local tcp = assert(socket.tcp())
tcp:connect(host, port);
tcp:send("hello world");
It is only supposed to connect to it, send some data and receive some in return.
Can someone help me fix it?
Your server is likely receiving per line. As noted in the receive docs, this is the default receiving pattern. Try adding a newline to your client message. This completes the receive on the server:
local host, port = "127.0.0.1", 100
local socket = require("socket")
local tcp = assert(socket.tcp())
tcp:connect(host, port);
--note the newline below
tcp:send("hello world\n");
while true do
local s, status, partial = tcp:receive()
print(s or partial)
if status == "closed" then break end
end
tcp:close()

Simple socket program in Ruby

I want to write a simple server socket in Ruby, which, when a client connects to it, prints a message and closes the client connection. I came up with:
require 'socket'
server = TCPServer.open('localhost',8800)
loop {
client = server.accept
Thread.start do
s = client
s.puts "Closing the connection. Bye!"
s.close
end
}
However, when I access "localhost:8800" in my browser, I am not getting that message, instead, it says page not found.. What am I doing wrong here?
It is quite likely that your browser is expecting something on the remote end that talks Http.
This is dependant upon your browser and also the exact URI you typed in. It is also possible that your browser is connecting getting the connection close and then displaying an error page.
If you want to see the server working then use telnet from a command prompt. So in one window type ruby ./myfilename.rb and then in another type telnet localhost 8800

Resources