C#で、シリアル通信をする
シリアル(RS-232C)で受けて電文変えてSocketで転送する機会があったので、C#のSerialPortクラスを使って実装してみました。
http://www.microsoft.com/japan/msdn/netframework/skillup/core/article2.aspx
サンプルはシリアル通信の入出力の部分だけです。上記サイトのコピペから、エラー処理とかを追加して作りました。
テストはcom0comを利用して仮想のCOMポートを作成し、1台のPCで行いました。TeraTermでも受けられるので便利です。
Null-modem emulator (com0com) - virtual serial port driver for Windows
- メッセージを送信し、エコーを受ける
using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; class Program { static void Main(string[] args) { while (true) { Console.Write("message>> "); string req = Console.ReadLine(); SerialPort port = new SerialPort("COM20", 9600, Parity.None, 8, StopBits.One); try { port.Open(); port.DtrEnable = true; port.RtsEnable = true; port.WriteLine(req); Console.WriteLine("send message :" + req); Console.WriteLine("received echo:" + port.ReadLine()); } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } port.Close(); port.Dispose(); } } }
- メッセージを受信し、エコーを返す
using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; class Program { static void Main(string[] args) { SerialPort port = new SerialPort("COM21", 9600, Parity.None, 8, StopBits.One); port.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived); try { port.Open(); port.DtrEnable = true; port.RtsEnable = true; } catch (Exception e) { Console.WriteLine("Unexpected exception : {0}", e.ToString()); } Console.ReadLine(); port.Close(); port.Dispose(); } private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort port = (SerialPort)sender; byte[] buf = new byte[1024]; int len = port.Read(buf, 0, 1024); string s = Encoding.GetEncoding("Shift_JIS").GetString(buf, 0, len); port.WriteLine(s); Console.Write("received message:" + s); Console.Write("send echo :" + s); } }