技術共有

シリアルポートからTCPへ①

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

形状

効果: クライアントまたはサーバーがメッセージを送信すると、シリアル ポートとネットワーク ポートの横のパネルが点滅します。ハートビート メカニズムのラジオ ボタンをオンまたはオフにすると、下のテキスト ボックスの数が増加します。ハートビート間隔と内容を設定できます。リセット ボタンはシリアル ポート データをリセットし、保存ボタンはシリアル ポート データを保存します (グループ ボックス: プロンプト ボックス、パネル、パネル、コンボ ボックス ドロップダウン ボックス、ラジオ ボタン、ラジオ ボタン、チェック ボックス、複数選択ボックス)

ini ファイル:

デバッグパスにファイルを作成し、ファイルにSetting.iniを作成します

構成ファイルを読み取ります:

文字列 dirPath = Path.Combine(Application.StartupPath, "File");

文字列 filePath = Path.Combine(dirPath, "Setting.ini");

Ini = 新しい IniHelper(filePath);

  1. namespace SerialportToTCP
  2. {
  3. public partial class Form1 : Form
  4. {
  5. IniHelper Ini;
  6. string[] botelvs = new string[] { "1200", "4800", "9600", "13200" };
  7. public Form1()
  8. {
  9. InitializeComponent();
  10. //1 读取配置文件
  11. string dirPath = Path.Combine(Application.StartupPath, "File");// debug/file
  12. string filePath = Path.Combine(dirPath, "Setting.ini");// debug / file/setting.ini
  13. Ini = new IniHelper(filePath); //创建读取对象
  14. // 添加串口
  15. comboBox1.Items.AddRange(SerialPort.GetPortNames());// 获取所有串口 拼接在下拉框的items中
  16. comboBox2.Items.AddRange(botelvs);// 添加波特率数组
  17. comboBox2.Items.Add("自定义");//添加一个
  18. comboBox3.Items.AddRange(new string[] { "5", "6", "7", "8" });
  19. comboBox4.Items.AddRange(new string[] { "无", "奇校检", "偶校检" });
  20. comboBox5.Items.AddRange(new string[] { "无", "1", "2", "1.5" });
  21. //2开始处理串口接受数据事件
  22. //处理串口的数据
  23. this.serialPort1.DataReceived = SerialPort1_DataReceived;
  24. //3 处理界面显示默认值 也就是从ini文件读取数据
  25. readSetting();
  26. //4 开始串口通信
  27. startChuanKou();
  28. //5 开始网口通信
  29. startTCP();
  30. }
  31. //开始搭建TCP服务器
  32. TcpListener listen;