TCPサーバーを書く必要があったので復習で書いてみた。
とりあえず、対話式の通信ではなく、一歩的にデータを送信してくる相手の通信をログに残している。
Wiresharkみたいなパケットキャプチャツールをログは良いかもしれない
同期型であまり役に立たないかな…
次は、非同期とか、複数のクライアントの管理なんかをやりたいけど。思いっきり忘れているので、Qiitaあさりをしたいと思います。いい例があったらコメントに書いて下さい。
でも、ライブラリのインポートをみると始めにいろいろとやろうとした意志だけは感じる
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_PORT = 60000;
static void Main(string[] args)
{
IPEndPoint ipaddress = new IPEndPoint(IPAddress.Parse(IP_ADDRESS), OPEN_PORT);
TcpListener listener = new TcpListener(ipaddress);
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() + "_" + DateTime.Now.ToString() + ".log";
StreamWriter writer = new StreamWriter(file_name);
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);
}
} while (client.Connected);
client.Close();
writer.Close();
}
Console.WriteLine("何かのキーを押すと終了");
Console.Read();
}
}
}