LoginSignup
3
3

More than 5 years have passed since last update.

tcpipによる接続サンプル

Last updated at Posted at 2014-12-11

一対一しか考えてませんがな。制御系のやつらなら大体これがあればクライアント側はどうにかなる。サーバー側のマルチスレッド化はそのうちするかもしんまい。
スリープの入れ方がダサいですが、知らんわ。

サーバー

require "socket"

CONNECTPORT = ARGV[0].to_i
puts CONNECTPORT
# クライアントからの接続を待つソケット
s0 = TCPServer.open(CONNECTPORT)

# クライアントからの接続をacceptする
sock = s0.accept

# 常に繰り返す
while true

  begin
    sock.puts("fff")
    # クライアントからのデータを全て受け取る
    buff,sp = sock.recvfrom(100)
    puts "--d #{buff}" if buff.length != 0
  rescue Exception => e
    puts "例外でたよ"
    sock = s0.accept
  end

end

# クライアントからの接続を待つソケットを閉じる
# ただし、ここに到達することはありません。
s0.close

クライアント

require "socket"
exit if ARGV.size != 2

IPADDRES = ARGV[0]
CONNECTPORT = ARGV[1].to_i
puts IPADDRES
puts CONNECTPORT

sock = nil
#ヘルスのファイル
sendque = Queue.new

# 受信処理
Thread.fork do
  while true
    begin
      if sock == nil
        # ソケット接続
        sock = TCPSocket.open(IPADDRES, CONNECTPORT)
      elsif false == sock.closed?
        rev,buff = sock.recvfrom(100)
        text = rev.chomp
        if text.length != 0
          puts "return message:" + text.unpack('C*').map{ |b| "0x%02X" % b }.join(' ')
        end
      else
        sock = TCPSocket.open(IPADDRES, CONNECTPORT)
      end
    rescue Exception => e
      sleep(1)
      puts "例外dana"
    end
    sleep(1)
  end
end

#亭周期送信情報
Thread.fork do
  health =  File.open("health.dat").read
  while true
    begin
      sendque.enq health
    rescue
      puts "例外でたよ"
    end
    sleep(3)
  end
end

# 送信処理
Thread.fork do
  sleep(1)
  begin
    if sock == nil
    elsif false == sock.closed?
      while req = sendque.pop
        print("you writed:", req.unpack('C*').map{ |b| "0x%02X" % b }.join(' '),"\n")
        sock.write(req)
      end
    end
  rescue
    puts "まぁ、例外でたよ"
  end
end

# ショット
while file_name = STDIN.gets.chomp
  msg = file_name
  if File.exist?(file_name)
    File.open(file_name) do |f|
      msg = f.read
      f.close
    end
  end
  sendque.enq msg
end
# 送信が終わったらソケットを閉じる
sock.close

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3