sample tcp client/server

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/local/bin/ruby
require 'socket'
# Pre-defined constants
M = 6400
REPLY_SIZE = 64
REQUEST_SIZE = 64
# Command line arguements
N = ARGV[0].to_i
server = TCPServer.new("localhost", 11000)
fork do
# Child runs client process
client = TCPSocket.new("localhost", 11000)
sum = 0
count = 0
request = "\x0" * REQUEST_SIZE
buffer = "\x0" * REPLY_SIZE
(M*N).times do
client.write(request)
c=0
while c < REPLY_SIZE
c += client.read(buffer.size, buffer).size
end
sum += c
count += 1
end
client.close
puts "replies: #{count} bytes: #{sum}"
end
# Server runs in parent
socket = server.accept
buffer = "\x0" * REQUEST_SIZE
reply = "\x0" * REPLY_SIZE
while not socket.eof?
socket.read(REQUEST_SIZE, buffer)
socket.write(reply)
end
socket.close
server.close