[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Help with Socket (TCPServer) requested!

Bill Kelly

9/9/2007 9:22:00 PM


From: "Victor Reyes" <victor.reyes@gmail.com>
>
> Basically, I would like the server side to start and block itself waiting
> for a request from a client.
> The client will connect and request a service such as execute a command on
> the servers side and return the output.
> I am having heck of a time trying to get a simple sample program to work.
> The connection is actually established, but I don't see the string that I
> sent the server and I don't get anything back on the client either.
>
> Here is my "server", please don't laugh!
>
> require 'socket'
> port = 19557
> server = TCPServer.new('localhost', port)
>
> while (session = server.accept)
> puts "Inside while..."
> puts session.to_s
> session.close
> end
>
>
> This is suppose to be the client:
>
> require 'socket'
> streamSock = TCPSocket.new( 'localhost', 19557 )
>
> streamSock.send( "Hello\n" )
> str = streamSock.recv( 100 )
> print str
> streamSock.close

NOTE: It appears your server neither attempts to send, nor receive
any data. (For example: data = session.gets; session.puts "got it")

If your goal is to specifically learn more about the sockets
API, there are several topics you'll want to explore:

- low-level (send/recv) vs. high-level (read/write/gets/puts) calls
- for instance: send & recv are not guaranteed to process as many
bytes as you ask, but will tell you how many they DID process

- blocking vs. non-blocking io semantics

- determining when IO is ready for reading or writing
- select() vs. threads

However, if your goal is to just start *using* sockets without
necessarily being burdened by some of the esoteric details and
trade-offs, you might be interested in EventMachine:

http://rubyforge.org/projects/ev...

EventMachine not only makes network I/O easier to deal with,
it's also a high performance library. So you won't be sacrificing
speed for ease of use.

EventMachine also supports protocol helper modules that you can
use to mix-in higher level functionality than just sending and
receiving byte stream bursts.

For example, if you were writing a line-based protocol, like
POP3, SMTP, or FTP, you could start with:

class MyProtocol < EventMachine::Protocols::LineAndTextProtocol

def receive_line(line)
# eventmachine LineAndTextProtcol will call your
# receive_line method when a full line is received
# for you to process
end

def send_line(line)
line += "\n" unless line[-1] == ?\n # add EOL if not present
send_data(line)
end

end

EventMachine::start_server host, port, MyProtocol


Regards,

Bill