require 'socket'
class Server_for_RM
attr_reader :run_times
def initialize(ip,port)
@run_times = 0
start_server(ip,port)
end
# 这个函数是从ruby教科书上抄的
def start_server(ip,port)
server = TCPServer.new(ip,port)
loop do
Thread.start(server.accept) do |client|
text = client.recv_nonblock(1024)
print "#{@run_times}\nAccepted connection from #{client.peeraddr[2]}\n\t>>#{text}\n"
text_r = return_msg(text)
# "&|--|&":分割符;
# rand().to_s:增长数据;
# "over":数据结尾
client.puts text_r+"&|--|&"+rand().to_s+"over"
print "\t<<#{text_r}\n"
print "Closing connection to #{client.peeraddr[2]}\n\n"
client.close
@run_times += 1
end
end
end
# 处理数据的函数
def return_msg(text)
# 除去传来数据末尾的over
text.gsub!(/over$/,"")
# 如果传来的数据是'XXX+XXX'
if text =~ /^[0-9]+\+[0-9]+$/
ary = text.split("+")
return "#{ary[0].to_i+ary[1].to_i}"
else
return text
end
end
end
# 这里修改ip和端口
Server_for_RM.new('127.0.0.1',9701)
require 'socket'
class Server_for_RM
attr_reader :run_times
def initialize(ip,port)
@run_times = 0
start_server(ip,port)
end
# 这个函数是从ruby教科书上抄的
def start_server(ip,port)
server = TCPServer.new(ip,port)
loop do
Thread.start(server.accept) do |client|
text = client.recv_nonblock(1024)
print "#{@run_times}\nAccepted connection from #{client.peeraddr[2]}\n\t>>#{text}\n"
text_r = return_msg(text)
# "&|--|&":分割符;
# rand().to_s:增长数据;
# "over":数据结尾
client.puts text_r+"&|--|&"+rand().to_s+"over"
print "\t<<#{text_r}\n"
print "Closing connection to #{client.peeraddr[2]}\n\n"
client.close
@run_times += 1
end
end
end
# 处理数据的函数
def return_msg(text)
# 除去传来数据末尾的over
text.gsub!(/over$/,"")
# 如果传来的数据是'XXX+XXX'
if text =~ /^[0-9]+\+[0-9]+$/
ary = text.split("+")
return "#{ary[0].to_i+ary[1].to_i}"
else
return text
end
end
end
# 这里修改ip和端口
Server_for_RM.new('127.0.0.1',9701)