9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# SimpleTCP 簡単なソケット通信プログラミング

Last updated at Posted at 2019-10-29

0. 本稿について

@BrandonPotter 氏の__SimpleTCP__(github)を用いたソケットサーバー、ソケットクライアントアプリケーションを作成する。

1. 環境 ~Environment~

  • Microsoft Visual Studio 2019 Community
  • .Net Framework 4.7.2
  • SimpleTCP 1.0.24

2. 導入 ~Installing SimpleTCP~

NuGetパッケージの管理から__「SimpleTCP」__をインストールする。
SimpleTCP.png

3. ソケットサーバを作成

下記のソケットサーバをフォームアプリケーションで作成する

  • IPアドレス:__すべてのIPアドレス__からの通信を受信する
  • 通信ポート:55555
  • 終端文字:0x00
  • 受信した電文メッセージに__「_Reply」__を追加し、送信先に返却する
  • 受信した電文メッセージをテキストボックスに表示する
SimpleTCPServerForm
using System.Windows.Forms;
using SimpleTCP;

namespace SimleTCPServer
{
    public partial class Form1 : Form
    {
        SimpleTcpServer server;
        const byte NULL_TERMINATED = 0x00;
        const int PORT = 55555;

        public Form1()
        {
            InitializeComponent();
            server= new SimpleTcpServer().Start(PORT);
            server.Delimiter = NULL_TERMINATED;
            server.DelimiterDataReceived += (sender, msg) => {
                 msg.ReplyLine(msg.MessageString + "_Reply");
                 textBox1.Text += "Receive::" + msg.MessageString;
            };
        }
    }
}

4. ソケットクライアントを作成

下記のソケットクライアントをフォームアプリケーションで作成する

  1. 特定のIPアドレス,ポートでListen接続待機しているソケットサーバに接続する。
  2. 接続したソケットサーバにメッセージに終端文字__0x00__を付与した文字列データを送信する。
  3. 送信後、返答を__3__秒間待機する。
  4. 返答メッセージをテキストボックスに表示する。
SimpleTCPClientForm
using System;
using System.Windows.Forms;
using SimpleTCP;

namespace SimpleTCPClient
{
    public partial class SimpleTCPClientForm : Form
    {
        public SimpleTCPClientForm()
        {
            InitializeComponent();
        }

        private void button_SendMsg_Click(object sender, EventArgs e)
        {
            var client = new SimpleTcpClient().Connect(textBox_IP.Text, int.Parse(textBox_Port.Text));
            textBox_RecieveMsg.Text += "Send::" + textBox_SendMsg.Text + Environment.NewLine;
            //終端文字を追加する。
            var replyMsg = client.WriteLineAndGetReply(textBox_SendMsg.Text + '\0', TimeSpan.FromSeconds(3));
            textBox_RecieveMsg.Text += "Reply::" + replyMsg.MessageString;
        }
    }
}

5.検証

ソケットクライアントからソケットサーバへ電文メッセージ("test")を送信し、応答メッセージ("test_Reply")を受信していることが分かる

SimpleTCP_Test.gif

99. 参考

SimpleTCP

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?