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.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace SocketServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//定义回调:解决跨线程访问问题
private delegate void SetTextValueCallBack(string strValue);
//定义接收客户端发送消息的回调
private delegate void ReceiveMsgCallBack(string strReceive);
//声明回调
private SetTextValueCallBack setCallBack;
//声明
private ReceiveMsgCallBack receiveCallBack;
//定义回调:给ComboBox控件添加元素
private delegate void SetCmbCallBack(string strItem);
//声明
private SetCmbCallBack setCmbCallBack;
//定义发送文件的回调
private delegate void SendFileCallBack(byte[] bf);
//声明
private SendFileCallBack sendCallBack;
//用于通信的Socket
Socket socketSend;
//用于监听的SOCKET
Socket socketWatch;
//将远程连接的客户端的IP地址和Socket存入集合中
Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
//接收客户端发送消息的线程
Thread threadReceive;
//创建监听连接的线程
Thread AcceptSocketThread;
//创建用于监听SOcket是否关闭的线程
Thread closeSocket;
//创建用于发送数据的线程
Thread SendMsgThread;
Log log = new Log("D:\\IIS" + @"/log/Log.txt");
private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
if (dicSocket.Count == 0)
{ }
else
{
foreach (var item in dicSocket)
{
string cjdz = "11,12";
string[] achara = cjdz.Split(',');
foreach (var item2 in achara)
{
if (dicSocket[item.Key].Poll(10, SelectMode.SelectRead))
{
string strReceiveMsg = "断开:" + dicSocket[item.Key].RemoteEndPoint;
string a = dicSocket[item.Key].RemoteEndPoint.ToString();
dicSocket[item.Key].Close();
txt_Log.Invoke(receiveCallBack, strReceiveMsg);
cmb_Socket.Items.Remove(a);
log.log("监听出错:" + strReceiveMsg + ",时间" + DateTime.Now);
dicSocket.Remove(a);
break;
}
else
{
string seceond = Convert.ToInt16(item2).ToString("x2") + FourOrderGas;
string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
byte[] sixmsg = HexStrTobyte(Last);
dicSocket[item.Key].Send(sixmsg);
string strReceiveMsg = "发送:" + dicSocket[item.Key].RemoteEndPoint + "发送的消息:" + Last + "时间" + DateTime.Now;
log.log("监听出错:" + strReceiveMsg + ",时间" + DateTime.Now);
this.textBox4.AppendText(strReceiveMsg + " \r \n");
}
}
}
}
}
catch (Exception ex)
{
this.textBox5.AppendText("给客户端接收消息线程出错:" + ex.Message + " \r \n");
}
}
private void btn_Start_Click(object sender, EventArgs e)
{
//当点击开始监听的时候 在服务器端创建一个负责监听IP地址和端口号的Socket
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取ip地址
IPAddress ip = IPAddress.Parse(this.txt_IP.Text.Trim());
//创建端口号
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txt_Port.Text.Trim()));
//绑定IP地址和端口号
socketWatch.Bind(point);
this.txt_Log.AppendText("监听成功" + " \r \n");
btn_Start.Enabled = false;
btn_StopListen.Enabled = true;
//开始监听:设置最大可以同时连接多少个请求
socketWatch.Listen(10);
//实例化回调
setCallBack = new SetTextValueCallBack(SetTextValue);
receiveCallBack = new ReceiveMsgCallBack(ReceiveMsg);
setCmbCallBack = new SetCmbCallBack(AddCmbItem);
sendCallBack = new SendFileCallBack(SendFile);
//创建线程
AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));
AcceptSocketThread.IsBackground = true;
Control.CheckForIllegalCrossThreadCalls = false;
AcceptSocketThread.Start(socketWatch);
#region 访问网站
System.Timers.Timer timer = new System.Timers.Timer();
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimedEvent);
timer.Interval = 10000;//每5秒执行一次
timer.Enabled = true;
#endregion
}
/// <summary>
/// 等待客户端的连接,并且创建与之通信用的Socket
/// </summary>
/// <param name="obj"></param>
int a = 1;
private void StartListen(object obj)
{
Socket socketWatch = obj as Socket;
while (true)
{
int c=a++;
//等待客户端的连接,并且创建一个用于通信的Socket
socketSend = socketWatch.Accept();
//获取远程主机的ip地址和端口号
string strIp = socketSend.RemoteEndPoint.ToString();
dicSocket.Add(strIp, socketSend);
this.cmb_Socket.Invoke(setCmbCallBack, strIp);
cmb_Socket.SelectedIndex = cmb_Socket.Items.IndexOf("socketSend.RemoteEndPoint");
string strMsg = "远程主机:" + socketSend.RemoteEndPoint + "连接成功";
//使用回调
txt_Log.Invoke(setCallBack, strMsg);
//定义接收客户端消息的线程
threadReceive = new Thread(new ParameterizedThreadStart(Receive));
threadReceive.IsBackground = true;
threadReceive.Start(socketSend);
closeSocket = new Thread(new ParameterizedThreadStart(closeSocketJT)); //监听是否正常关闭
closeSocket.IsBackground = true;
Control.CheckForIllegalCrossThreadCalls = false;
closeSocket.Start(socketSend);
}
}
private void closeSocketJT(object obj) //监听是否正常关闭的线程
{
Socket socketSend = obj as Socket;
while (true)
{
if (socketSend.Poll(10, SelectMode.SelectRead))
{
string strReceiveMsg = "断开:" + socketSend.RemoteEndPoint;
string a = socketSend.RemoteEndPoint.ToString();
dicSocket[a].Close();
txt_Log.Invoke(receiveCallBack, strReceiveMsg);
cmb_Socket.Items.Remove(a);
dicSocket.Remove(a);
break;
}
else
{
}
}
}
/// <summary>
/// 服务器端不停的接收客户端发送的消息
/// </summary>
/// <param name="obj"></param>
private void Receive(object obj)
{
Socket socketSend = obj as Socket;
int c = 0;
string a = "";
while (true)
{
//}
//客户端连接成功后,服务器接收客户端发送的消息
try
{
byte[] buffer = new byte[2048];
if (socketSend.Poll(10, SelectMode.SelectRead))
{
string strReceiveMsg = "断开:" + socketSend.RemoteEndPoint;
string b = socketSend.RemoteEndPoint.ToString();
dicSocket[b].Close();
txt_Log.Invoke(receiveCallBack, strReceiveMsg);
cmb_Socket.Items.Remove(b);
dicSocket.Remove(b);
break;
}
else
{
int count = socketSend.Receive(buffer);
if (count == 0)//count 表示客户端关闭,要退出循环
{
break;
}
else
{
string str = Encoding.Default.GetString(buffer, 0, count);
string sixbyte = byteToHexStr(buffer, count);
string g = sixbyte.Substring(6, 8);
string cjdz = sixbyte.Substring(0,2);
int b = Int32.Parse(cjdz, System.Globalization.NumberStyles.HexNumber);
byte[] byteArray = HexStrTobyte(g);
byte[] COD = new byte[4] { byteArray[1], byteArray[0], byteArray[3], byteArray[2] };
if (sixbyte.Length == 18)
{
c = c + b;
if (c == b)
{
string strReceiveMsg2 = "接收:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() + "时间" + DateTime.Now;
txt_Log.Invoke(receiveCallBack, strReceiveMsg2);
a += b + "," + Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString();
FirstOrderGasOrder(socketSend, sixbyte);
}
if (c == 2*b)
{
SecondOrderOrder(socketSend, sixbyte);
string strReceiveMsg = "接收:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() + "时间" + DateTime.Now;
a += "," + Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString() + ",";
txt_Log.Invoke(receiveCallBack, strReceiveMsg);
}
if (c == 3 * b)
{
temperatureOrder(socketSend, sixbyte);
string strReceiveMsg = "接收:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() + "时间" + DateTime.Now;
a += Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString() + ",";
txt_Log.Invoke(receiveCallBack, strReceiveMsg);
}
if (c == 4 * b)
{
humidityOrder(socketSend, sixbyte);
string strReceiveMsg = "接收:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() + "时间" + DateTime.Now;
a += Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString() + ",";
txt_Log.Invoke(receiveCallBack, strReceiveMsg);
}
if (c == 5 * b)
{
string strReceiveMsg = "接收:" + socketSend.RemoteEndPoint + "发送的消息:" + BitConverter.ToSingle(COD, 0).ToString() + "时间" + DateTime.Now;
a += Math.Round(BitConverter.ToSingle(COD, 0), 2).ToString().ToString();
txt_Log.Invoke(receiveCallBack, strReceiveMsg);
txt_Log.Invoke(receiveCallBack, a);
c = 0;
a = "";
//txt_Log.Text = "";
//textBox4.Text = "";
}
}
//FirstOrderGasOrder(socketSend, sixbyte);
}
}
}
catch (Exception ex)
{
this.textBox5.AppendText("给客户端接收消息线程出错:" + ex.Message + " \r \n");
//MessageBox.Show("给客户端接收消息线程出错:" + ex.Message);
//socketSend.Close();
break;
}
}
}
private void SendUrl(string a)
{
string[] achara = a.Split(',');
String str = "192.168.0.115:8089" + "appport/SHISHI" + "?FormId=" + achara[0]+ "&&Oxygen=" + achara[1] + "&&HydrogenSulfide=" + achara[2] + "&&Temperature=" + achara[3] + "&&Humidity="+achara[4];
string param = "";
byte[] bs = Encoding.ASCII.GetBytes(param);
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(str);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bs.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
//FileStream fs = new FileStream("c:\\easyTouch\\新建文件夹\\定时访问.txt", FileMode.Append);
//StreamWriter sw = new StreamWriter(fs, Encoding.Default);
//sw.Write("访问完成>>>>>>>>>>>>>:" + DateTime.Now);
//sw.Close();
//fs.Close();
}
using (WebResponse wr = req.GetResponse())
{
//在这里对接收到的页面内容进行处理
}
}
#region //定时执行事件
private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e,object a)
{
try
{
byte[] sixmsg = HexStrTobyte("05 03 04 4E 00 02 A4 A8");
dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
}
catch (Exception E)
{
throw;
}
}
#endregion
// 字节数组转16进制字符串
public static string byteToHexStr(byte[] bytes,int count)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < count; i++)
{
returnStr += bytes[i].ToString("X2");//ToString("X2") 为C#中的字符串格式控制符
}
}
return returnStr;
}
/// <summary>
/// 回调委托需要执行的方法
/// </summary>
/// <param name="strValue"></param>
private void SetTextValue(string strValue)
{
this.txt_Log.AppendText(strValue + " \r \n");
}
private void ReceiveMsg(string strMsg)
{
this.txt_Log.AppendText(strMsg + " \r \n");
}
private void AddCmbItem(string strItem)
{
this.cmb_Socket.Items.Add(strItem);
}
private void btn_Send_Click_Click(object sender, EventArgs e)
{
try
{
if (socketSend.Poll(10, SelectMode.SelectRead))
{
string strReceiveMsg = "断开:" + socketSend.RemoteEndPoint;
string a = socketSend.RemoteEndPoint.ToString();
dicSocket[a].Close();
txt_Log.Invoke(receiveCallBack, strReceiveMsg);
cmb_Socket.Items.Remove(a);
dicSocket.Remove(a);
}
else
{
string strMsg = this.txt_Msg.Text.Trim();
byte[] buffer = Encoding.Default.GetBytes(strMsg);
List<byte> list = new List<byte>();
list.Add(0);
list.AddRange(buffer);
//将泛型集合转换为数组
byte[] newBuffer = list.ToArray();
//获得用户选择的IP地址
string ip = this.cmb_Socket.SelectedItem.ToString();
byte[] sixmsg = HexStrTobyte(strMsg);
dicSocket[ip].Send(sixmsg);
}
}
catch (Exception ex)
{
MessageBox.Show("给客户端发送消息:" + ex.Message);
//string ip = this.cmb_Socket.SelectedItem.ToString();
//dicSocket[ip].Close();
//this.cmb_Socket.Items.Remove(ip);
}
//socketSend.Send(buffer);
}
// 16进制字符串转字节数组 格式为 string sendMessage = "00 01 00 00 00 06 FF 05 00 64 00 00";
private static byte[] HexStrTobyte(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).Trim(), 16);
return returnBytes;
}
private void btn_Select_Click(object sender, EventArgs e)
{
OpenFileDialog dia = new OpenFileDialog();
//设置初始目录
dia.InitialDirectory = @"";
dia.Title = "请选择要发送的文件";
//过滤文件类型
dia.Filter = "所有文件|*.*";
dia.ShowDialog();
//将选择的文件的全路径赋值给文本框
this.txt_FilePath.Text = dia.FileName;
}
private void btn_SendFile_Click(object sender, EventArgs e)
{
List<byte> list = new List<byte>();
//获取要发送的文件的路径
string strPath = this.txt_FilePath.Text.Trim();
using (FileStream sw = new FileStream(strPath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[2048];
int r = sw.Read(buffer, 0, buffer.Length);
list.Add(1);
list.AddRange(buffer);
byte[] newBuffer = list.ToArray();
//发送
//dicSocket[cmb_Socket.SelectedItem.ToString()].Send(newBuffer, 0, r+1, SocketFlags.None);
btn_SendFile.Invoke(sendCallBack, newBuffer);
}
}
private void SendFile(byte[] sendBuffer)
{
try
{
dicSocket[cmb_Socket.SelectedItem.ToString()].Send(sendBuffer, SocketFlags.None);
}
catch (Exception ex)
{
MessageBox.Show("发送文件:" + ex.Message);
}
}
private void btn_Shock_Click(object sender, EventArgs e)
{
byte[] buffer = new byte[1] { 2 };
dicSocket[cmb_Socket.SelectedItem.ToString()].Send(buffer);
}
private void btn_StopListen_Click(object sender, EventArgs e)
{
try
{
//string ip = this.cmb_Socket.SelectedItem.ToString();
//for (int i = 0; i < dicSocket.Count; i++)
//{
// dicSocket[ip].Close();
//}
//dicSocket[ip].Close();
threadReceive.Abort();
foreach (var item in dicSocket)
{
dicSocket[item.Key].Close();
}
socketWatch.Close();
socketSend.Close();
AcceptSocketThread.Abort();
this.txt_Log.AppendText("停止监听成功" + " \r \n");
this.cmb_Socket.Items.Clear();
//cmb_Socket.Items.Clear();
btn_Start.Enabled = true;
btn_StopListen.Enabled = false;
}
catch(Exception ex)
{ MessageBox.Show("终止线程:" + ex.Message); }
终止线程
//AcceptSocketThread.Abort();
//threadReceive.Abort();
}
private void clear_Click(object sender, EventArgs e)
{
txt_Log.Text = "";
textBox4.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
byte[] byteArray = HexStrTobyte(change.Text);
byte[] COD = new byte[4] { byteArray[1], byteArray[0], byteArray[3], byteArray[2] };
textBox2.Text= BitConverter.ToSingle(COD, 0).ToString();
}
string[] Order = { "03 01 4E 00 02", "03 02 4E 00 02", "03 04 4E 00 02", "03 00 1F 00 02", "03 00 22 00 02"};
public string FirstOrderGas = "03 01 4E 00 02";
public string SecondOrderGas = "03 02 4E 00 02";
public string FourOrderGas = "03 04 4E 00 02";
public string temperature = "03 00 1F 00 02";
public string humidity = "03 00 21 00 02";
#region
private void FirstOrderGasOrder(object obj, string a)
{
try
{
Socket socketSend = obj as Socket;
string b = a;
string seceond = b.Substring(0, 2) + FirstOrderGas;
string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
byte[] sixmsg = HexStrTobyte(Last);
Thread.Sleep(500);
dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
string strReceiveMsg = "发送:" + dicSocket[socketSend.RemoteEndPoint.ToString()].RemoteEndPoint + "发送的消息:" + Last + "时间" + DateTime.Now;
this.textBox4.AppendText(strReceiveMsg + " \r \n");
}
catch (Exception e)
{ }
}
private void SecondOrderOrder(object obj, string a)
{
try
{
Socket socketSend = obj as Socket;
string b = a;
string seceond = b.Substring(0, 2) + SecondOrderGas;
string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
byte[] sixmsg = HexStrTobyte(Last);
Thread.Sleep(500);
dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
string strReceiveMsg = "发送:" + dicSocket[socketSend.RemoteEndPoint.ToString()].RemoteEndPoint + "发送的消息:" + Last + "时间" + DateTime.Now;
this.textBox4.AppendText(strReceiveMsg + " \r \n");
}
catch (Exception e)
{ }
}
private void temperatureOrder(object obj, string a)
{
try
{
Socket socketSend = obj as Socket;
string b = a;
string seceond = b.Substring(0, 2) + temperature;
string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
byte[] sixmsg = HexStrTobyte(Last);
Thread.Sleep(500);
dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
string strReceiveMsg = "发送:" + dicSocket[socketSend.RemoteEndPoint.ToString()].RemoteEndPoint + "发送的消息:" + Last + "时间" + DateTime.Now;
this.textBox4.AppendText(strReceiveMsg + " \r \n");
}
catch (Exception e)
{ }
}
private void humidityOrder(object obj, string a)
{
try
{
Socket socketSend = obj as Socket;
string b = a;
string seceond = b.Substring(0, 2) + humidity;
string Last = seceond + CRC16.CRC.ToModbusCRC16(seceond, true);
byte[] sixmsg = HexStrTobyte(Last);
Thread.Sleep(500);
dicSocket[socketSend.RemoteEndPoint.ToString()].Send(sixmsg);
string strReceiveMsg = "发送:" + dicSocket[socketSend.RemoteEndPoint.ToString()].RemoteEndPoint + "发送的消息:" + Last + "时间" + DateTime.Now;
this.textBox4.AppendText(strReceiveMsg + " \r \n");
}
catch (Exception e)
{ }
}
#endregion
public class SB_GasDetails
{
public int FormId { get; set; }
public decimal Oxygen { get; set; }
public decimal HydrogenSulfide { get; set; }
public decimal Ammonia { get; set; }
public decimal Temperature { get; set; }
public decimal Humidity { get; set; }
public DateTime Pubdate { get; set; }
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text=dicSocket.Count.ToString();
}
private void button3_Click(object sender, EventArgs e)
{
textBox3.Text= CRC16.CRC.ToModbusCRC16(textBox3.Text, true);
}
#region Log文件
public class Log
{
private string logFile;
private StreamWriter writer;
private FileStream fileStream = null;
public Log(string fileName)
{
logFile = fileName;
CreateDirectory(logFile);
}
public void log(string info)
{
try
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(logFile);
if (!fileInfo.Exists)
{
fileStream = fileInfo.Create();
writer = new StreamWriter(fileStream);
}
else
{
fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write);
writer = new StreamWriter(fileStream);
}
writer.WriteLine(DateTime.Now + ": " + info + " \r \n");
}
finally
{
if (writer != null)
{
writer.Close();
writer.Dispose();
fileStream.Close();
fileStream.Dispose();
}
}
}
public void CreateDirectory(string infoPath)
{
DirectoryInfo directoryInfo = Directory.GetParent(infoPath);
if (!directoryInfo.Exists)
{
directoryInfo.Create();
}
}
}
#endregion
}
}
气体仪器WinForm代码(服务器端)
最新推荐文章于 2023-12-25 11:10:03 发布