using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using Timer = System.Timers.Timer;
namespace Core.StlMes.Client.LgResMgt.Mcms
{
public class SocketClient : iCommunication
{
private Socket _socketClient;
private Task sendTask;
private readonly Timer timer = new Timer();
public SocketClient()
{
timer.Elapsed += timer_Elapsed;
timer.Interval = 1 * 5 * 1000;
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)//判断是否连接成功
{
if(_socketClient==null) return;
if (Reconnecting) return;
if (Status && !Reconnect)
{
if (_socketClient.Connected)
{
try
{
byte[] temp = new byte[1]{0x00};
// _socketClient.Send(temp, 0, 0);
Reconnect = false;
}
catch (SocketException ex)
{
if (ex.NativeErrorCode.Equals(10035)) //仍然是connect的
Reconnect = false;
else
Reconnect = true;
}
Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
test.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
}
catch (SocketException ex)
{
if (ex.NativeErrorCode.Equals(10035)) //仍然是connect的
Reconnect = false;
else
Reconnect = true;
}
finally
{
test.Disconnect(false);
test.Shutdown(SocketShutdown.Both);
test.Close();
}
}
else
{
Reconnect = true;
}
}
//连接已经断开
if (Reconnect)
{
Reconnecting = true;
OnReceiveDataA("0", "服务器断开,重量清0!", DataType.ReceiveData);
OnReceiveDataA("0", "服务器断开,重新连接!", DataType.ClientReconnect);
if (Status)
{
try
{
if (_socketClient != null)
{
_socketClient.Shutdown(SocketShutdown.Both);
_socketClient.Close();
_status = false;
}
}
catch (Exception)
{
}
}
try
{
_socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接服务器
_socketClient.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
//请求获取数据
_socketClient.Send(new byte[] { 0xE6, 0X00, 0XE7 });
byte[] buffer = new byte[2048];
_socketClient.ReceiveTimeout = 5000;
int count = _socketClient.Receive(buffer);
if (count <= 0 || !(buffer[0] == 0xE6 && buffer[1] == 0x00 && buffer[2] == 0xE7))
{
return;
}
_status = true;
Reconnect = false;
sendTask = new Task(() => StartReceive());
sendTask.Start();
OnReceiveDataA("", string.Format("开启监听 ip:{0} 端口:{1} ", Ip, Port), DataType.Open);
}
catch (Exception)
{
}
Reconnecting = false;
}
}
public void Start()
{
try
{
//实例化socket
_socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//连接服务器
_socketClient.Connect(new IPEndPoint(IPAddress.Parse(Ip), int.Parse(Port)));
//请求获取数据
// _socketClient.Send(new byte[] { 0xE6, 0X00, 0XE7 });---
// byte[] buffer = new byte[2048];--
// _socketClient.ReceiveTimeout = 5000;--
// int count = _socketClient.Receive(buffer);--
/*
if (count <= 0 || !(buffer[0] == 0xE6 && buffer[1] == 0x00 && buffer[2] == 0xE7))
{
MessageBox.Show("请求远程服务器失败!");
return;
}*/
// timer.Start();
_status = true;
Reconnect = false;
_socketClient.Blocking = true;
sendTask = new Task(() => StartReceive());
sendTask.Start();
//OnReceiveDataA("", string.Format("开启监听 ip:{0} 端口:{1} ", Ip, Port), DataType.Open);
}
catch (Exception ex)
{
OnReceiveData(null, ex.Message, DataType.Error);
}
}
///
/// 采用Socket方式,测试服务器连接
///
/// 服务器主机名或IP
/// 端口号
/// 等待时间:毫秒
///
public static bool TestConnection(string host, int port)
{
int millisecondsTimeout = 5;//等待时间
TcpClient client = new TcpClient();
try
{
var ar = client.BeginConnect(host, port, null, null);
ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
return client.Connected;
}
catch (Exception e)
{
throw e;
}
finally
{
client.Close();
}
}
public void Stop()
{
try
{
if (_socketClient != null)
{
_socketClient.Shutdown(SocketShutdown.Both);
_socketClient.Close();
}
}
catch (Exception)
{
}
_status = false;
Reconnect = false;
timer.Stop();
// OnReceiveDataA("", "断开与服务器的连接 ", DataType.Close);
}
///
/// 开启接收
///
///
private void StartReceive()
{
var ReceiveData = new List();
while (Status && !Reconnect)//
{
try
{
byte[] buffer = new byte[2048];
int count = _socketClient.Receive(buffer);
if (count > 0)
{
var Datas = buffer.ToList().Take(count);
ReceiveData = ReceiveData.Concat(Datas).ToList();
object Data;
DeframeType Result = DeframeType.UnKnow;
while (ReceiveData.Any() && Result != DeframeType.LengthLess)
{
List rightData;
Result = _protocol.AnalaysData(ReceiveData, out Data, out rightData);
if (Result != DeframeType.RightFrame && Result != DeframeType.LengthLess) ReceiveData.Clear();
if (Result == DeframeType.RightFrame)
{
OnReceiveData(Data, "成功解析数据!" + Data.ToString(), DataType.ReceiveData, rightData.ToArray());
}
if (Result == DeframeType.WrongFrame)
{
OnReceiveData(null, "数据解析失败", DataType.EvenMessage);
}
}
}
}
catch (Exception ex)
{
// MessageBox.Show(ex.ToString());
}
}
}
public event ReceiveDataHandler ReceiveData;
private IProtocol _protocol;
public void ChangeProtocol(IProtocol iProtocol)
{
_protocol = iProtocol;
}
private bool _status;
public bool Status {
get { return _status || Reconnect; }
}
public bool Reconnect { get;private set; }
public bool Reconnecting { get; private set; }
protected virtual void OnReceiveData(object data, string message, DataType dataType, byte[] bData = null)
{
var handler = ReceiveData;
if (handler != null)
new Task(() => { handler(this, data, message, dataType, bData);
if (dataType == DataType.ReceiveData)
{
double wt;
if (double.TryParse(data.ToString2(), out wt))
{
WeightValue = (wt / 100d).ToString("0.00") + "t";
};
}
}).Start();
// handler(this, data, DeviceName + " " + message);
}
protected virtual void OnReceiveDataA(object data, string message, DataType dataType, byte[] bData = null)
{
var handler = ReceiveData;
if (handler != null)
handler(this, data, message, dataType, bData);
// handler(this, data, DeviceName + " " + message);
}
public string Ip { get; set; }
// public string SportNo { get; set; } //点位信息
public bool Show { get; set; }//是否显示
public string Port { get; set; }
public string WeightValue { get; set; }//重量信息
public override string ToString()
{
return "远程服务器[" + Ip + ":" + Port + "] ";
}
}
}