From: tammy roberts2 Date: 2012-08-21T11:17:43+09:00 Subject: Re: TCPserver how to signal EOT Robert Klemme wrote in post #1072878: > On Mon, Aug 20, 2012 at 11:57 AM, tammy roberts2 > wrote: >> Hi Robert, it is me again, my computer crashed and I lost my login >> information. Here is what I am using right now, it seems to be working >> fine, but maybe you see problems with it or a way to improve. Also maybe >> it will help someone else out who is struggling with the same problem I >> was. > > This is a completely different approach: you do not use a termination > byte any more but transmit the message length beforehand. >> data_received = [] >> end >> >> def send_data(socket, message) >> forward_message = [message.bytesize].pack('N*') + message >> socket.send(forward_message, 0) >> yield(socket) >> end > > Why do you yield the socket? So that it can be passed to the get_reply method if the client expects a reply from the server, or closed by the calling method if it does not. >> yield(reply, socket) >> end >> end > > If you use #send then I'd also use #read for reading instead of > #recvfrom. I'd only use that method if I needed the extra options. > Method #read will also block until as many bytes have arrived so you > do not take care of fragment messages yourself. So am I correct in thinking that if I use read I do not need to put it in a loop because it will always wait until that many bytes have arrived? > I'd probably choose a tad different approach by wrapping the > connection with something that does the message handling and creation > of a message type (for specific parsing etc.): The listen method currently yields to the caller an array with the parts of the data that has been transmitted to it, and the calling method then knows how to process this array depending on what it is (the message type). > # could be more sophisticated > Message = Struct.new :bytes > > Connection = Struct.new :socket do > def send(msg) > b = msg.bytes > socket.write [b.bytesize].pack 'N' > socket.write b > self > end > > def close > socket.close > end > > def each_msg > until socket.eof? > size = socket.read(4).unpack('N').first > msg = socket.read(size) > yield Message.new(msg) > end > end > > self > end > end > > loop do > Thread.new(server.accept) do |client| > conn = Connection.new client > > conn.each_msg do |msg| > yield msg, conn > end > end > end > > > Kind regards > > robert Thanks for your advice I will be seriously considering the way you presented this :). -- Posted via http://www.ruby-forum.com/.