view daemon/Connection.cs @ 23:46cfeb0609c5

Add TcpConnections
author riono <e165729@ie.u-ryukyu.ac.jp>
date Tue, 15 Dec 2020 22:11:40 +0900
parents 970c7f587126
children 0cd2684e401b
line wrap: on
line source

using System;
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Net.Sockets;
using Christie_net.codegear;
using Christie_net.datagear.command;

namespace Christie_net.daemon {
public class Connection {
    public Socket socket;
    public string name;
    public CodeGearManager cgm;
    public BlockingCollection<Command> sendQueue = new BlockingCollection<Command>();
    public bool sendManager = true;
    private object syncObject = new object();
    
    public Connection(Socket socket, CodeGearManager cgm) {
        this.socket = socket;
        this.cgm = cgm;
    }
    
    public Connection(){}

    public void SendCommand(Command cmd) {
        sendQueue.TryAdd(cmd);
    }

    /// <summary>
    /// socketが接続しているhostnameとそのport番号を返す
    /// </summary>
    /// <returns></returns>
    public string GetInfoString() {
        return Dns.GetHostEntry(((IPEndPoint) socket.LocalEndPoint).Address.ToString()).HostName + ":" +
                ((IPEndPoint) socket.LocalEndPoint).Port;
    }

    /// <summary>
    /// socketを閉じる
    /// </summary>
    public void Close() {
        socket.Shutdown(SocketShutdown.Both);
        socket.Close();
    }

    /// <summary>
    /// commandの実装に従ってbyte配列に変換し接続先に書き込む
    /// </summary>
    /// <param name="cmd"></param>
    public void Write(Command cmd) {
        MemoryStream stream = cmd.Convert();
        byte[] buffer = stream.ToArray();

        try {
            while (stream.Length > 0) {
                socket.Send(buffer);
            }
        } catch (Exception e) {
            Console.WriteLine(e.StackTrace); 
        }
    }
}
}