Skip to content

Instantly share code, notes, and snippets.

@ochilab
Created June 24, 2016 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ochilab/25ae59c53e8ff31be3141a2209416e16 to your computer and use it in GitHub Desktop.
Save ochilab/25ae59c53e8ff31be3141a2209416e16 to your computer and use it in GitHub Desktop.
C# TCP接続通信
//TcpClientを作成し、サーバーと接続する
TcpClient tcp = new TcpClient("localhost", 10000);
Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。",
((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address,
((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port,
((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address,
((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port);
//NetworkStreamを取得する
NetworkStream ns = tcp.GetStream();
//読み取り、書き込みのタイムアウトを10秒にする
ns.ReadTimeout = 10000;
ns.WriteTimeout = 10000;
//サーバーにデータを送信する
//文字列をByte型配列に変換
string input = Console.ReadLine();
string sendMsg = input;
System.Text.Encoding enc = System.Text.Encoding.ASCII;
byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
//データを送信する
ns.Write(sendBytes, 0, sendBytes.Length);
MemoryStream ms = new MemoryStream();
int resSize = 0;
do{
byte[] resBytes = new byte[256];
byte[] data = new byte[256];
//サーバーから送られたデータを受信する
resSize = ns.Read(resBytes, 0, resBytes.Length);
//Readが0を返した時はサーバーが切断したと判断
if (resSize == 0){
Console.WriteLine("サーバーが切断しました。");
break;
}
//受信したデータを蓄積する
ms.Write(data, 0, resSize);
//受信したデータを文字列に変換
string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
resMsg.Replace("\0", "");
Console.WriteLine(resMsg);
System.Diagnostics.Debug.Write(resMsg);
} while (ns.DataAvailable)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment