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&