moix
moix

Reputation: 11

TCPServer socket in ruby

I would like to establish a connection between 2 computers using socket. For this purpose one of them is a server and this is the code I've write:

sock= TCPServer.open('localhost', 6666)
sock.accept

the client try to establish the connection:

client = TCPSocket.open(ip_server, 6666)

but is not working. I've notice scanning server's ports that the server does not open the port to the network, only works in local mode.

Any suggestion, thk in advance

Upvotes: 1

Views: 2491

Answers (4)

AShelly
AShelly

Reputation: 35600

I've used this code successfully. Server side:

serverSocket = TCPServer.new( "", port )
serverSocket.accept

and on the client

t = TCPSocket.new(server_ip, port.to_i)  

However, recently I've started using the 'EventMachine' gem, which made handling sockets 10 times easier

Upvotes: 3

stslavik
stslavik

Reputation: 3028

It's already been said that the service is running in "Local Mode" using the loopback "localhost".

sock= TCPServer.open('localhost', 6666)
sock.accept

TCPServer is a handy interface for the underlying file descriptor. Frankly, it almost makes socket programming too easy.

Like what has already been said, 'localhost' is a loopback to 127.0.0.1. Therefore, your statement is equivalent to:

sock= TCPServer.open('127.0.0.1', 6666)
sock.accept

If you will be using the network connection on a local network, assuming the server has an assigned IP of 192.168.0.1, you can assign a local IP address to listen on:

sock= TCPServer.open('192.168.0.1', 6666)
sock.accept

For an open port, conceivably open to all, use:

sock= TCPServer.open(6666)
sock.accept

Remember that everything is a file – the connection you're making is reading and writing to the same file or series of files from two (or more) locations. It's important to control who might have access to those files, and to what extent.

Upvotes: 1

Eimantas
Eimantas

Reputation: 49354

It works in "local mode" because it listens on localhost wich is loopback address for the computer the server is launched in. The IP address of your server should be address your computer has on local network (something like 192.168.x.x).

Upvotes: 0

jigfox
jigfox

Reputation: 18177

Yes, and it allright so, because you said it should bind the server port to the interface of 'localhost' and this is 127.0.0.1 and is bind to your loopback interface and not to any real interface connecting to the realworld.

You should try

sock = TCPServer.new(6666)
sock.accept

Upvotes: 0

Related Questions