标签:sop stat welcome reac substring oca main mmu 等于
串口通讯:
using CommunicationInterfaceForm.Script;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CommunicationInterfaceForm
{
public partial class MainForm : Form
{
public SerialPort com = new SerialPort();
//定义端口类
private SerialPort ComDevice = new SerialPort();
private SqlConnDB sqlcline = new SqlConnDB();
public MainForm()
{
InitializeComponent();
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
//初始化数据
comboBox2.Text = "9600";
comboBox5.Text = "0";
comboBox3.Text = "8";
comboBox4.Text = "1";
InitralConfig(int.Parse(comboBox2.Text));
}
/// <summary>
/// 从注册表获取系统串口列表
/// </summary>
public string[] GetComList()
{
RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
string[] sSubKeys = keyCom.GetValueNames();
string[] str = new string[sSubKeys.Length];
for (int i = 0; i < sSubKeys.Length; i++)
{
str[i] = (string)keyCom.GetValue(sSubKeys[i]);
}
return str;
}
/// <summary>
/// 配置初始化
/// </summary>
private void InitralConfig(int btl)
{
Boolean open = false;
string[] coms = GetComList();
for (int i = 0; i < coms.Length; i++)
{
open = false;
if (com.IsOpen)
{
com.Close();
}
comboBox1.Items.Add(coms[i]);
}
if (comboBox1.Items.Count >= 0) {
comboBox1.SelectedIndex = 0;
}
//向ComDevice.DataReceived(是一个事件)注册一个方法Com_DataReceived,当端口类接收到信息时时会自动调用Com_DataReceived方法
ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
/// <summary>
/// 一旦ComDevice.DataReceived事件发生,就将从串口接收到的数据显示到接收端对话框
/// </summary>
/// <param name="sender"></param>
/// <param name="sender"></param>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//开辟接收缓冲区
byte[] ReDatas = new byte[ComDevice.BytesToRead];
//从串口读取数据
ComDevice.Read(ReDatas, 0, ReDatas.Length);
//实现数据的解码与显示
AddData(ReDatas);
}
/// <summary>
/// 解码过程
/// </summary>
/// <param name="data">串口通信的数据编码方式因串口而异,需要查询串口相关信息以获取</param>
public void AddData(byte[] data)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sb.AppendFormat("{0:x2}" + " ", data[i]);
}
AddContent(sb.ToString());//.ToUpper()
}
/// <summary>
/// 接收端对话框显示消息
/// </summary>
/// <param name="content"></param>
private void AddContent(string content)
{
BeginInvoke(new MethodInvoker(delegate
{
textBox1.AppendText(content);
}));
//将数据保存到数据库
if (!string.IsNullOrWhiteSpace(content))
{
string sql = string.Format("insert into test (Content,Equipment) values (‘{0}‘,‘假装是设备‘)", content);
int a = sqlcline.update(sql);
if (a == -1)
{
MessageBox.Show("连接数据库错误");
}
}
}
/// <summary>
/// 串口开关
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.Items.Count <= 0)
{
MessageBox.Show("未发现可用串口,请检查硬件设备");
return;
}
if (ComDevice.IsOpen == false)
{
//设置串口相关属性
ComDevice.PortName = comboBox1.Text;
ComDevice.BaudRate = Convert.ToInt32(comboBox2.Text);
ComDevice.Parity = (Parity)Convert.ToInt32(comboBox5.Text);
ComDevice.DataBits = Convert.ToInt32(comboBox3.Text);
ComDevice.StopBits = (StopBits)Convert.ToInt32(comboBox4.Text);
try
{
//开启串口
ComDevice.Open();
button2.Enabled = true;
button1.Text = "关闭";
//接收数据
ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "未能成功开启串口", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
try
{
ComDevice.Close();
button2.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "串口关闭错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
button1.Text = "开启";
}
comboBox1.Enabled = !ComDevice.IsOpen;
comboBox2.Enabled = !ComDevice.IsOpen;
comboBox3.Enabled = !ComDevice.IsOpen;
comboBox4.Enabled = !ComDevice.IsOpen;
comboBox5.Enabled = !ComDevice.IsOpen;
}
/// <summary>
/// 将消息编码并发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
byte[] sendData = null;
sendData = Hex16StringToHex16Byte(textBox1.Text);
SendData(sendData);
}
/// <summary>
/// 此方法用于将16进制的字符串转换成16进制的字节数组
/// </summary>
/// <param name="_hex16ToString">要转换的16进制的字符串。</param>
public static byte[] Hex16StringToHex16Byte(string _hex16String)
{
//去掉字符串中的空格。
_hex16String = _hex16String.Replace(" ", "");
if (_hex16String.Length / 2 == 0)
{
_hex16String += " ";
}
//声明一个字节数组,其长度等于字符串长度的一半。
byte[] buffer = new byte[_hex16String.Length / 2];
for (int i = 0; i < buffer.Length; i++)
{
//为字节数组的元素赋值。
buffer[i] = Convert.ToByte((_hex16String.Substring(i * 2, 2)), 16);
}
//返回字节数组。
return buffer;
}
/// <summary>
/// 此函数将编码后的消息传递给串口
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public bool SendData(byte[] data)
{
if (ComDevice.IsOpen)
{
try
{
//将消息传递给串口
ComDevice.Write(data, 0, data.Length);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "发送失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("串口未开启", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
/// <summary>
/// 16进制编码
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private byte[] strToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0) hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
return returnBytes;
}
}
}
socket通讯
using httpClient.script;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Management;
namespace httpClient
{
enum AgreeType
{
UDP,
TCP
}
public partial class Form1 : Form
{
private static SqlConnDB sqlcline = new SqlConnDB();
TCPClient tc = new TCPClient();
private static byte[] result = new byte[1024];
static Socket serverSocket;
Thread myThread;
//udp的socket
private static Socket udpServer;
//tcp的socket
private static Socket clientSocket;
public Form1()
{
InitializeComponent();
comboBox1.SelectedIndex = 0;
comboBox3.Items.Add(GetAddressIP());
comboBox3.SelectedIndex = 0;
}
/// <summary>
/// 获取本地IP
/// </summary>
/// <returns></returns>
private string GetAddressIP()
{
string AddressIP = string.Empty;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
{
AddressIP = _IPAddress.ToString();
}
}
return AddressIP;
}
private void button1_Click(object sender, EventArgs e)
{
if (string.Equals(button1.Text, "连接"))
{
switch (comboBox1.SelectedIndex)
{
case (int)AgreeType.TCP:
//服务器IP地址
IPAddress ip = IPAddress.Parse(GetAddressIP());
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, Convert.ToInt32(textBox2.Text)));
//绑定IP地址:端口
serverSocket.Listen(10);
//设定最多10个排队连接请求
textBox1.AppendText(string.Format("启动监听{0}成功", serverSocket.LocalEndPoint.ToString()));
//通过Clientsoket发送数据
myThread = new Thread(ListenClientConnect);
myThread.Start();
//ListenClientConnect();
break;
case (int)AgreeType.UDP:
//1.Socket creat
udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//2.Bind ip and port
udpServer.Bind(new IPEndPoint(IPAddress.Parse(GetAddressIP()),Convert.ToInt32(textBox2.Text)));
//3.receive data
new Thread(UdpRecivceMsg) {IsBackground = true}.Start();
break;
default:
break;
}
button1.Text = "关闭";
comboBox1.Enabled = false;
comboBox3.Enabled = false;
textBox2.Enabled = false;
}else
{
button1.Text = "连接";
comboBox1.Enabled = true;
comboBox3.Enabled = true;
textBox2.Enabled = true;
if (string.Equals(comboBox1.Text, "TCP"))
{
close();
}
if (string.Equals(comboBox1.Text, "UDP"))
{
udpServer.Close();
}
}
}
#region udp实例
private void UdpSendMsg(string msg)
{
Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse(GetAddressIP()), 9999);
byte[] data = Encoding.UTF8.GetBytes(msg);
udpClient.SendTo(data, serverPoint);
}
/// <summary>
/// 接收数据
/// </summary>
private static void UdpRecivceMsg()
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
//MessageBox.Show("1111");
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);
//将数据保存到数据库
//MessageBox.Show("eee");
//此方法把数据来源ip、port放到第二个参数中
string message = Encoding.UTF8.GetString(data, 0, length);
MessageBox.Show("从ip" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port + "Get" + message);
if (!string.IsNullOrWhiteSpace(message))
{
string sql = string.Format("insert into test (Content,Equipment) values (‘{0}‘,‘假装是设备‘)", message);
int a = sqlcline.update(sql);
if (a == -1)
{
MessageBox.Show("连接数据库错误");
}
}
}
}
#endregion
#region tcp实例
/// <summary>
/// /// 监听客户端连接
/// /// </summary>
private static void ListenClientConnect()
{
while (true)
{
clientSocket = serverSocket.Accept();
clientSocket.Send(Encoding.ASCII.GetBytes("Hello,welcome to my new world!"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientSocket);
}
}
/// <summary>
/// 发送消息
/// </summary>
private static void SendMessage(string msg)
{
clientSocket.Send(Encoding.ASCII.GetBytes(msg));
}
/// <summary>
/// /// 接收消息
/// /// </summary>
/// /// <param name="clientSocket"></param>
private static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientSocket接收数据
int receiveNumber = myClientSocket.Receive(result);
MessageBox.Show(string.Format("接收客户端{0}消息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber)));
if (!string.IsNullOrWhiteSpace(Encoding.ASCII.GetString(result, 0, receiveNumber)))
{
string sql = string.Format("insert into test (Content,Equipment) values (‘{0}‘,‘假装是设备‘)", Encoding.ASCII.GetString(result, 0, receiveNumber));
int a = sqlcline.update(sql);
if (a == -1)
{
MessageBox.Show("连接数据库错误");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
public void close()
{
serverSocket.Close();
myThread.Abort();
}
#endregion
private void button2_Click(object sender, EventArgs e)
{
if (string.Equals(comboBox1.Text,"TCP")) {
SendMessage(textBox1.Text);
}
else {
UdpSendMsg(textBox1.Text);
}
}
}
}
通讯方式
标签:sop stat welcome reac substring oca main mmu 等于
原文地址:https://www.cnblogs.com/ganzhihui/p/11531510.html