気になった事を自由に書いてます。
      
TCP/IP タイムアウトを設定して受信すると・・・②
前回は受信するときにタイムアウトが発生すると、同時に例外も発生し切断状態になって
困ってました。
詳しく調べてないので断言できませんが、これは仕様なのかもしれません。
なのでタイムアウト発生で切断となるのは個人的に嫌なので、他の方法を試しました。

受信メソッドを実行すると何か受信するまでずっと固まる(同期?)ので
メインスレッドでは呼び出せない。。ではサブスレッドで受信してやれば・・・

TCPClient
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

private TcpClient _tcp = null;
private NetworkStream _ns = null;

public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        // TCP/IP接続
        _tcp = new TcpClient("192.168.24.52", 4567);

        // ストリーム取得
        _ns = _tcp.GetStream();

        // 受信開始
        ReceiveProcStart();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

private void button2_Click(object sender, EventArgs e)
{
    // 送信データ
    string sendText = "AAA";

    // 送信データをByte型配列に変換
    byte[] sendByte = System.Text.Encoding.UTF8.GetBytes(sendText);

    // データ送信
    _ns.Write(sendByte, 0, sendByte.Length);
}

private void ReceiveProcStart()
{
    Thread thread = new Thread(ReceiveProc);
    thread.Start();
}

private void ReceiveProc()
{
    try
    {
        while (true)
        {
            // 受信データの読み出し
            byte[] buf = new byte[100];
            int len = _ns.Read(buf, 0, buf.Length);
            string s = System.Text.Encoding.UTF8.GetString(buf, 0, len);
            Console.WriteLine("受信:" + s);

            // 送信データ
            string sendText = "BBB";

            // 送信データをByte型配列に変換
            byte[] sendByte = System.Text.Encoding.UTF8.GetBytes(sendText);

            // データ送信
            _ns.Write(sendByte, 0, sendByte.Length);

        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

これでアプリが固まらずに受信できるようになりました。
      




Effective C# 4.0
ビル・ワグナー
¥ 3,780



Copyright (C) 2011 - 2017 猫の気ままなC#日記