You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

282 lines
7.3 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using EAS.HFWinderServer.Base;
using EC.Entity;
using EAS.HFWinderServer.Code.PLC;
/*******************************************************/
/*
项目: HFCQMES
模块:
描述: Socket通讯
版本: 1.0
日期: 2015.09.12
作者: 刘晓春
更新:
TODO: */
/*******************************************************/
namespace Eas.Client.Code.SocketServer
{
public class SocketPLCServer1
{
private FrmServerBase frmMain;
private Boolean canlistening = false ;
private int port = MESConfig.SOCKET_PORT;
List<Socket> socketLst = new List<Socket>();
public delegate void mydelegate(string str);
public SocketPLCServer1(FrmServerBase frmmainsvr)
{
frmMain = frmmainsvr;
Thread LisThread = new Thread(new ThreadStart(StartListening));
LisThread.Start();
}
private ManualResetEvent allDone = new ManualResetEvent(false);
public void StartListening()
{
canlistening = true;
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port);
Socket listener = null ;
try
{
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
catch(SocketException ex)
{
Log( ex.Message,true);
return;
}
try
{
listener.Bind(localEndPoint);
listener.Listen(110);
Log("服务监听端口" + port);
while (canlistening)
{
allDone.Reset();
listener.BeginAccept(new AsyncCallback(acceptCallback), listener);
allDone.WaitOne(); //阻塞主线程
}
}
catch (Exception ex)
{
Log("listener.Bind=" + ex.ToString());
}
finally
{
listener.Close();
Log("finally 停止接收",true);
}
}
public void acceptCallback(IAsyncResult ar)
{
if (canlistening == false)
{
return;
}
try
{
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
String ip = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();
//设置主线程继续
allDone.Set();
StateObject state = new StateObject();
state.workSocket = handler;
socketLst.Add(handler);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(readCallback), state);
}
catch (Exception ex)
{
Log(ex.Message,true);
}
}
public void readCallback(IAsyncResult ar)
{
if (canlistening == false)
{
return;
}
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
IPEndPoint clientip = (IPEndPoint)handler.RemoteEndPoint;
String ip = clientip.Address.ToString();
int read = handler.EndReceive(ar);
if (read > 0)
{
//处理接收到的命令
StocketDataWinderPLCHandler micHandler = new StocketDataWinderPLCHandler(state.buffer, 0, read,null);
Log("clientip:" + ip + " rec: " + micHandler.ReadDataString);
if (handler.Connected)
{
try
{
string responseData =micHandler.GetResponseText();
Log("clientip:" + ip + " send: " + responseData);
handler.Send(Encoding.UTF8.GetBytes(responseData));
}
catch (Exception ex)
{
FileUnit.Log(ex.Message);
handler.Close();
handler = null;
return;
}
}
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(readCallback), state);
}
else
{
if (state.sb.Length > 1)
{
string content = state.sb.ToString();
FileUnit.Log(string.Format("Read {0} bytes from socket.\n Data:{1}", content.Length, content));
}
handler.Close();
handler = null;
}
}
catch (Exception ex)
{
Log( ex);
}
}
#region 输出日志
private void Log(Exception ex) {
Log(ex.Message, true);
}
/// <summary>
///
/// </summary>
/// <param name="message">信息</param>
/// <param name="isErr">是否是错误</param>
private void Log(string message, bool isErr = false)
{
if (isErr)
{
LogUnit.Error(this.GetType(), message);
}
else
{
LogUnit.Debug(this.GetType(), message);
}
if (frmMain != null)//当有主窗体时 输出
{
frmMain.ShowMsg(message);
}
}
#endregion
private void RefeshSocketList()
{
FileUnit.Log("MIC RefeshSocketLst len=" + socketLst.Count);
for (int x = socketLst.Count-1; x >=0; x--)
{
Socket socket = socketLst[x];
if (socket != null)
{
if (socket.Connected == false)
{
socket = null;
socketLst.RemoveAt(x);
}
}
else
{
socketLst.RemoveAt(x);
}
}
}
public void Stop()
{
canlistening = false;
allDone.Set();
for (int x = 0; x < socketLst.Count; x++)
{
Socket socket = socketLst[x];
if (socket != null)
{
socket.Close();
}
}
socketLst.Clear();
}
public void ShowClient()
{
Log("Count:" + socketLst.Count);
for (int x = 0; x < socketLst.Count; x++)
{
Socket socket = socketLst[x];
if (socket != null)
{
Log(socket.Connected.ToString());
}
else Log("null");
}
}
}
}