using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Mesnac.Basic
{
public class SocketClient
{
public static Socket m_clientSocket;
private byte[] m_receiveBuffer = new byte[1024];
private IPEndPoint remoteEndPoint;
public string receiveStr;
public bool connFlag = false;
public static string serverIp
{
get
{
return ConfigurationManager.AppSettings["ListenServerIP"];
}
}
public static string serverPort
{
get
{
return ConfigurationManager.AppSettings["Port"];
}
}
public SocketClient()
{
remoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIp), Convert.ToInt32(serverPort));
m_clientSocket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
public bool Connect()
{
bool reC = false;
try
{
IAsyncResult result = m_clientSocket.BeginConnect(remoteEndPoint, null, null);
result.AsyncWaitHandle.WaitOne(500);
//m_clientSocket.Connect(remoteEndPoint);
if (m_clientSocket.Connected)
{
reC = true;
connFlag = true;
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
}
}
catch
{
}
finally
{
}
return reC;
}
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
int REnd = m_clientSocket.EndReceive(ar);
string strReceiveData = Encoding.UTF8.GetString(m_receiveBuffer, 0, REnd);
this.HandleMessage(strReceiveData);
if (string.IsNullOrEmpty(strReceiveData))
{
connFlag = false;
}
else
{
m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
}
//m_clientSocket.BeginReceive(m_receiveBuffer, 0, m_receiveBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
}
catch (Exception ex)
{
connFlag = false;
}
}
///
/// 处理接收到的数据
///
private void HandleMessage(string message)
{
message = message.Replace("/0", "");
if (!string.IsNullOrEmpty(message))
{
receiveStr = message;
}
}
///
/// 客户端尝试重连服务器端
///
public void ReConnect()
{
try
{
if (m_clientSocket != null && m_clientSocket.Connected)
{
m_clientSocket.Close();
m_clientSocket.Disconnect(false);
m_clientSocket = null;
}
m_clientSocket.Close();
remoteEndPoint = new IPEndPoint(IPAddress.Parse(serverIp), Convert.ToInt32(serverPort));
m_clientSocket = new Socket(remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
this.Connect();
}
catch (System.Exception)
{
//logBundle.DBLog(App.FormName, 1, "网络已经断开", "");
}
}
}
}