using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.IO;
namespace Com
{
public class para
{
public SerialPort[] p;
}
class Program
{
//串口的读是以阻塞方式读取的.本机有两个com口,专门做数据中转调试.
static void Main(string[] args)
{
try
{
SerialPort port1 = new SerialPort();
port1.BaudRate = 115200;
port1.StopBits = StopBits.One;
port1.DataBits = 8;
port1.Encoding = Encoding.Unicode;
port1.PortName = "COM1";
port1.Open();
SerialPort port2 = new SerialPort();
port2.BaudRate = 115200;
port2.StopBits = StopBits.One;
port2.DataBits = 8;
port2.Encoding = Encoding.Unicode;
port2.PortName = "COM8";
port2.Open();
para ps = new para();
ps.p = new SerialPort[] { port1, port2 };
Thread th1 = new Thread(new ParameterizedThreadStart(SendToClient));
Thread th2 = new Thread(new ParameterizedThreadStart(SendToHost));
th2.Start(ps);
th1.Start(ps);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
while (true) ;
}
/// <summary>
/// 从com8 接收 向com1写
/// </summary>
/// <param name="p"></param>
public static void SendToClient(object ps)
{
FileStream file = File.Open(@"C:\Com1收到的数据.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(file);
para p = ps as para;
Byte[] bit = new Byte[4096];
while (true)
{
int r = p.p[0].Read(bit, 0, bit.Length);
p.p[1].Write(bit, 0, r);
while (--r >= 0)
{
string str = string.Format("0x{0:x} ", bit[r]);
sw.Write(str);
Console.WriteLine(str);
}
sw.WriteLine();
}
}
/// <summary>
/// 从com1 接收 向com8写
/// </summary>
/// <param name="p"></param>
public static void SendToHost(object ps)
{
FileStream file = File.Open(@"C:\Com8收到的数据.txt", FileMode.Create);
StreamWriter sw = new StreamWriter(file);
para p = ps as para;
Byte[] bit = new Byte[4096];
while (true)
{
int r = p.p[1].Read(bit, 0, bit.Length);
p.p[0].Write(bit, 0, r);
while (--r >= 0)
{
string str = string.Format("0x{0:x} ", bit[r]);
sw.Write(str);
Console.WriteLine(str);
}
sw.WriteLine();
}
}
}
}