TCP

簡単なTCPサーバー2

複数スレッドで複数ポートからの接続を待ち受けられるようにしてみた

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;


namespace SampleTCPServer
{
    class Program
    {
        readonly static string IP_ADDRESS = "192.168.0.1";
        readonly static int OPEN_PORT1 = 60000;
        readonly static int OPEN_PORT2 = 60001;
        readonly static int OPEN_PORT3 = 60002;
        readonly static int READ_PACKET_NUMBER = 100;

        static void Main(string[] args)
        {
            callTcpConnected(OPEN_PORT1);


            Task<bool> task1 = Task.Run<bool>(() =>
            {
                callTcpConnected(OPEN_PORT1);
                return true;
            });

            Task<bool> task2 = Task.Run<bool>(() =>
            {
                callTcpConnected(OPEN_PORT2);
                return true;
            });

            Task<bool> task3 = Task.Run<bool>(() =>
            {
                callTcpConnected(OPEN_PORT3);
                return true;
            });

            // とりあえず一番始めに起動したスレッドが終わるまで待つ
            var wait1 = task1.Result;

            Console.WriteLine("何かのキーを押すと終了");
            Console.Read();
        }

        /// <summary>
        /// 指定のポートで受信待ちをする
        /// </summary>
        /// <param name="open_port">開くポート番号</param>
        private static void callTcpConnected(int open_port)
        {
            IPEndPoint ip_end_point = new IPEndPoint(IPAddress.Parse(IP_ADDRESS), open_port);
            TcpListener listener = new TcpListener(ip_end_point);

            listener.Start();
            TcpClient client = listener.AcceptTcpClient();

            if (client.Connected)
            {
                listener.Stop();
                NetworkStream net_stream = client.GetStream();

                string file_name = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString() + "_" + open_port.ToString()
                                    + "_" + DateTime.Now.ToString() + ".log";

                StreamWriter writer = new StreamWriter(file_name);

                int counter = 0;

                do
                {
                    if (net_stream.CanRead)
                    {
                        byte[] recive_byte = new byte[client.ReceiveBufferSize];
                        net_stream.Read(recive_byte, 0, (int)client.ReceiveBufferSize);

                        writer.WriteLine(recive_byte);
                        counter++;
                    }

                    Thread.Sleep(10);
                } while (client.Connected && counter < READ_PACKET_NUMBER);
                client.Close();
                writer.Close();
            }
        }
    }
}