アットウィキロゴ

Network

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using System.Text.RegularExpressions;
 
namespace DesignProject
{
    class UDPMessage
    {
        //メッセージの種別
        public const int MESSAGE_INT = 0;
        public const int MESSAGE_STRING = 1;
        public const int MESSAGE_CHARACTER = 2;
        public const int MESSAGE_SYSTEM = 3;
 
        //システムメッセージの種別
        public const int SYSTEM_CONNECT = 0;
        public const int SYSTEM_CLOSE = 1;
 
 
        public int type { get; private set; }
        public int dataLength { get; private set; }
        public byte[] data { get; private set; }
 
        public UDPMessage(int type, byte[] data)
        {
            this.type = type;
            this.data = data;
            this.dataLength = data.Length;
        }
 
        public UDPMessage(byte[] data)
        {
            int index = 0;
 
            this.type = BitConverter.ToInt32(data, index);
            index += 4;
 
            this.dataLength = BitConverter.ToInt32(data, index);
            index += 4;
 
            this.data = new byte[this.dataLength];
            Array.ConstrainedCopy(data, index, this.data, 0, this.dataLength);
        }
 
        public byte[] ToByte()
        {
            byte[] result = new byte[4 + 4 + this.dataLength];
            int index = 0;
 
            byte[] temp = BitConverter.GetBytes(this.type);
            Array.ConstrainedCopy(temp, 0, result, index, temp.Length);
            index += temp.Length;
 
            temp = BitConverter.GetBytes(this.dataLength);
            Array.ConstrainedCopy(temp, 0, result, index, temp.Length);
            index += temp.Length;
 
            Array.ConstrainedCopy(this.data, 0, result, index, this.data.Length);
 
            return(result);
        }
 
        //データをint型へ変換
        public int DataToInt()
        {
            return (BitConverter.ToInt32(this.data, 0));
        }
 
        //データをstring型へ変換
        public string DataToString()
        {
            Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS");
            return (sjisEnc.GetString(this.data, 0, this.dataLength));
        }
 
        //データをCharacter型へ変換
        public Character DataToCharacter()
        {
            return(new Character(this.data));
        }
    }
 
    class UDPStateObject
    {
        public NetworkUDP network;
 
        public UDPStateObject(NetworkUDP network)
        {
            this.network = network;
        }
    }
 
    class NetworkUDP
    {
        private UdpClient udp;
        private IPEndPoint remote;
        public IPEndPoint clientEndPoint { get { return (this.isReceived ? this.remote : null); } }
        //private Queue<byte[]> sendDataQueue;
        private Queue<byte[]> receiveDataQueue;
        //public int sendCount { get { return (this.sendDataQueue.Count); } }
        public int receiveCount { get { return (this.receiveDataQueue.Count); } }
        private Thread receiveThread;
        public bool isReceived { get; private set; }
        public bool isClientEnd { get; private set; }
        public bool isReceiving { get; private set; }
 
        public NetworkUDP(int port)
        {
            this.udp = new UdpClient(port);
            //this.sendDataQueue = new Queue<byte[]>();
            this.receiveDataQueue = new Queue<byte[]>();
            this.receiveThread = null;
            this.isReceived = false;
            this.isClientEnd = false;
            this.isReceiving = false;
        }
 
        public void Close()
        {
            Console.WriteLine("CloseClient ");
            this.isClientEnd = true;
            if (this.isReceiving)
            {
                this.receiveThread.Abort();
                this.receiveThread.Join();
            }
            this.udp.Close();
 
        }
 
        private void Send(byte[] data, IPEndPoint endPoint)
        {
            Console.WriteLine("SendStart");
            this.udp.Send(data, data.Length, endPoint);
            Console.WriteLine("SendEnd");
        }
 
        //public void Send(byte[] data, string ipAddress, int port)
        //{
        //    Send(data, new IPEndPoint(IPAddress.Parse(ipAddress), port));
        //}
 
        //public void Send(int data, string ipAddress, int port)
        //{
        //    Send(BitConverter.GetBytes(data), new IPEndPoint(IPAddress.Parse(ipAddress), port));
        //}
 
        private void StartSend(byte[] data, IPEndPoint endPoint)
        {
            Console.WriteLine("SendStart");
            this.udp.BeginSend(data, data.Length, new AsyncCallback(SendCallback), new UDPStateObject(this));
        }
 
        private static void SendCallback(IAsyncResult ar)
        {
            UDPStateObject state = (UDPStateObject)(ar.AsyncState);
            if (!state.network.isClientEnd)
            {
                try
                {
                    int sendBytes = state.network.udp.EndSend(ar);
                    Console.WriteLine("SendEnd " + sendBytes);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message + e.TargetSite);
                }
            }
        }
 
        //int型のデータ送信用
        public void SendIntMessage(int data, IPEndPoint endPoint)
        {
            UDPMessage message = new UDPMessage(UDPMessage.MESSAGE_INT, BitConverter.GetBytes(data));
            Send(message.ToByte(), endPoint);
        }
 
        //string型のデータ送信用
        public void SendStringMessage(string data, IPEndPoint endPoint)
        {
            Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS");
            UDPMessage message = new UDPMessage(UDPMessage.MESSAGE_STRING, sjisEnc.GetBytes(data));
            Send(message.ToByte(), endPoint);
        }
 
        //Character型のデータ送信用
        public void SendCharacterMessage(Character data, IPEndPoint endPoint)
        {
            UDPMessage message = new UDPMessage(UDPMessage.MESSAGE_SYSTEM, data.ToByte());
            Send(message.ToByte(), endPoint);
        }
 
        //システムメッセージ送信用
        public void SendSystemMessage(int data, IPEndPoint endPoint)
        {
            UDPMessage message = new UDPMessage(UDPMessage.MESSAGE_SYSTEM, BitConverter.GetBytes(data));
            Send(message.ToByte(), endPoint);
        }
 
 
 
 
 
        private void StartReceive()
        {
            if (!this.isClientEnd)
            {
                this.udp.BeginReceive(ReceiveCallback, new UDPStateObject(this));
            }
        }
 
        private static void ReceiveCallback(IAsyncResult ar)
        {
            UDPStateObject state = (UDPStateObject)(ar.AsyncState);
            if (!state.network.isClientEnd)
            {
                try
                {
                    byte[] data = state.network.udp.EndReceive(ar, ref state.network.remote);
                    state.network.receiveDataQueue.Enqueue(data);
                    //state.network.data = state.network.udp.EndReceive(ar, ref state.network.remote);
                    //Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length));
                    Console.WriteLine(BitConverter.ToString(data));
                    Console.WriteLine("Received from " + state.network.remote.Address + ":" + state.network.remote.Port);
                    state.network.isReceived = true;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message + e.TargetSite);
                }
            }
        }
 
        private void RunReceive()
        {
            while (true)
            {
                StartReceive();
                Thread.Sleep(100);
            }
        }
 
        public void StartReceiveThread()
        {
            this.receiveThread = new Thread(new ThreadStart(this.RunReceive));
            this.receiveThread.Start();
            this.isReceiving = true;
            Console.WriteLine("ReceiveStart");
        }
 
        public byte[] GetReceiveData()
        {
            if (this.receiveDataQueue.Count != 0)
            {
                return (this.receiveDataQueue.Dequeue());
            }
            return (null);
        }
 
        public UDPMessage GetReceiveMessage()
        {
            if (this.receiveDataQueue.Count != 0)
            {
                return (new UDPMessage(this.receiveDataQueue.Dequeue()));
            }
            return (null);
        }
 
 
        static string clip = "";
 
        static void GetClipboardText()
        {
            if (Clipboard.ContainsText())
            {
                clip = Clipboard.GetText();
            }
        }
 
        public static IPEndPoint GetClipIP()
        {
            Thread t = new Thread(GetClipboardText);
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
 
            Regex regex = new Regex("(([0-9]{1,3})([.])([0-9]{1,3})([.])([0-9]{1,3})([.])([0-9]{1,3}))([:])([0-9]{1,5})");
            if (regex.IsMatch(clip))
            {
                string ip = regex.Match(clip).Groups[1].ToString();
                string port = regex.Match(clip).Groups[10].ToString();
                //Console.WriteLine(ip + ":" + port);
                return (new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)));
            }
            return(null);
        }
 
        public static void SetClipboardText()
        {
            Clipboard.SetText(GlobalIP.GetGIP.Get().ToString() + ":" + "10800");
        }
 
        public static void SetClipIP()
        {
            Thread t = new Thread(SetClipboardText);
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            t.Join();
        }
 
 
 
        public static int[] GetIPArray(IPEndPoint ip)
        {
            int[] ipport = new int[17];
            string str = ip.ToString();
            int writeIndex = 0;
            //int section = 2;
            Regex regex = new Regex("(([0-9]{1,3})([.])([0-9]{1,3})([.])([0-9]{1,3})([.])([0-9]{1,3}))([:])([0-9]{1,5})");
            if (regex.IsMatch(str))
            {
                for (int section = 2; section < 10; section += 2)
                {
                    string num = regex.Match(str).Groups[section].Value;
                    for (int i = 0; i < num.Length; i++)
                    {
                        ipport[writeIndex * 3 + 3 - num.Length + i] = int.Parse(num[i].ToString());
                    }
                    writeIndex += 1;
                }
                string port = regex.Match(str).Groups[10].Value;
                for (int i = 0; i < port.Length; i++)
                {
                    ipport[12 + i] = int.Parse(port[i].ToString());
                }
            }
            //for (int i = 0; i < 17; i++)
            //{
            //    Console.WriteLine(ipport[i]);
            //}
            return (ipport);
        }
 
        public static IPEndPoint GetIPFromArray(int[] array)
        {
            string ip = "";
            for (int i = 0; i < 4; i++)
            {
                if(i != 0){
                    ip += ".";
                }
                for (int j = 0; j < 3; j++)
                {
                    if (!((j == 0) && (array[i * 3 + j].ToString().Equals("0"))))
                    {
                        ip += array[i * 3 + j].ToString();
                    }
                }
            }
            string port = "";
            for(int i = 0; i < 5; i ++){
                port += array[12 + i].ToString();
            }
            return (new IPEndPoint(IPAddress.Parse(ip), int.Parse(port)));
        }
 
        public static string GetIPStringFromArray(int[] array)
        {
            string ip = "";
            for (int i = 0; i < 4; i++)
            {
                if (i != 0)
                {
                    ip += ".";
                }
                for (int j = 0; j < 3; j++)
                {
                    ip += array[i * 3 + j].ToString();
                }
            }
            string port = "";
            for (int i = 0; i < 5; i++)
            {
                port += array[12 + i].ToString();
            }
            return (ip + ":" + port);
        }
    }
}
 

タグ:

+ タグ編集
  • タグ:
最終更新:2011年01月17日 02:06
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。