# Tcp multiple client / server... for each connection write

**URL:** <https://www.ruby-forum.com/t/tcp-multiple-client-server-for-each-connection-write/167370>\
**Category:** Ruby\
**Created:** [May 7, 2009, 5:40am UTC](https://www.ruby-forum.com/t/tcp-multiple-client-server-for-each-connection-write/167370 "2009-05-07T05:40:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![i8igmac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/919ad9/32.png) [@i8igmac](https://www.ruby-forum.com/u/i8igmac)\
**Post date:** [May 7, 2009, 5:40am UTC](https://www.ruby-forum.com/t/tcp-multiple-client-server-for-each-connection-write/167370/1 "2009-05-07T05:40:41Z")

</div>

im putting together a server with multiple clients establishing a  
connection… I need each client connected to retreave a string from the  
server then the client’s will process this string… string = gets, this  
is how the server sends out the string but only the first client will  
process this string…  
I need the server to do something like this…

for each.connection.write(string)

does that make sense? im not sure how to accomplish this…

here is the source…

#server.rb  
require ‘socket’

server = TCPServer.new(1234)

loop do  
Thread.start(server.accept) do |connection|  
print connection  
str = gets  
connection.write(str)# this needs to stay alive or actave for  
each connection  
end  
end  
#---------------end of server-----------

#Client.rb  
require ‘socket’

while true  
sleep 1  
streamSock = TCPSocket.new( “127.0.0.1”, 1234 )  
var1,var2,var3 = streamSock.recv( 100 ).chomp.split

if var1 == ‘example’  
print var2+"\n"  
print var3+"\n"

elsif var1 == ‘test’  
print var2+"\n"  
print var3+"\n"

end  
end  
#-----------------end client-------------

---

<div class="post-metadata">

**Author:** ![i8igmac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/919ad9/32.png) [@i8igmac](https://www.ruby-forum.com/u/i8igmac)\
**Post date:** [May 7, 2009, 8:36am UTC](https://www.ruby-forum.com/t/tcp-multiple-client-server-for-each-connection-write/167370/2 "2009-05-07T08:36:18Z")

</div>

> for each.connection.write(string)

I’d probably make the server less multi-threaded, something like

all\_cons = []  
all\_cons \<\< server.accept  
all\_cons \<\< server.accept # now it has two connections.

Also look into the use of select.  
Cheers!  
-=r
