110,529
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 连接,一般用于客户端的创建
/// </summary>
/// <param name="ServerIP">Socket连接的IP地址</param>
/// <param name="Port">Socket连接的端口</param>
public void Connect(string ip, int port)
{
ConnectByParams(ip, port, DEFAULT_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
}
private void ConnectByParams(string ip, int port, int sendBufferSize, int receiveBufferSize)
{
_connIp = ip;
_connPort = port;
try
{
_SendBufferSize = sendBufferSize;
_ReceiveBufferSize = receiveBufferSize;
_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_Socket.SendBufferSize = _SendBufferSize;
_Socket.ReceiveBufferSize = _ReceiveBufferSize;
_Socket.NoDelay = true;
_ReceiveBuffer = new byte[_Socket.ReceiveBufferSize];
_Socket.BeginConnect(ip, port, new AsyncCallback(ConnectCallBack), _Socket);
}
catch (Exception ex)
{
if (ExceptionEvent != null)
ExceptionEvent(this, new SocketEventArgs(null, "连接失败:" + ex.Message));
this.Close();
}
}
private void ConnectCallBack(IAsyncResult iar)
{
try
{
iar.AsyncWaitHandle.Close();
if (!IsConnected)
throw new Exception("");
if (SocketConnectedEvent != null)
SocketConnectedEvent(this, true);
_Socket.BeginReceive(_ReceiveBuffer, 0, _ReceiveBuffer.Length, SocketFlags.None, acRcv, _Socket);
}
catch (Exception ex)
{
if (SocketConnectedEvent != null)
SocketConnectedEvent(this, false);
if (ExceptionEvent != null)
ExceptionEvent(this, new SocketEventArgs(null, "连接失败:" + ex.Message));
this.Close();
}
}
/// <summary>
/// 接收数据
/// </summary>
private void AsynRecvCallBack(IAsyncResult iar)
{
if (_Socket == null) return; //防止其他线程关闭Socket;
try
{
int nLen = _Socket.EndReceive(iar);
iar.AsyncWaitHandle.Close();
if (nLen <= 0) //使用接收0字节作为远端Socket断开的判断
{
if (SocketDisconnectedEvent != null)
SocketDisconnectedEvent(this, null);
this.Close();
}
else
{
byte[] m_ByteDatas = new byte[nLen];
Array.Copy(_ReceiveBuffer, 0, m_ByteDatas, 0, nLen);
if (ReceivedEvent != null)
ReceivedEvent(this, new SocketEventArgs(m_ByteDatas, null));
//继续接收
_Socket.BeginReceive(_ReceiveBuffer, 0, _ReceiveBuffer.Length, SocketFlags.None, acRcv, null);
}
}
catch (SocketException ex)
{
if (ExceptionEvent != null)
ExceptionEvent(this, new SocketEventArgs(null, "Type:" + ex.GetType().Name + ";ErrorCode:" + ex.ErrorCode.ToString() + ";Msg:" + ex.Message +
"\r\n" + ex.StackTrace));
if (ex.ErrorCode != 10035)
{
if (SocketDisconnectedEvent != null)
SocketDisconnectedEvent(this, null);
this.Close();
}
}
catch (Exception ex)
{
if (ExceptionEvent != null)
ExceptionEvent(this, new SocketEventArgs(null, ex.GetType().Name + ":" + ex.Message + "\r\n" + ex.StackTrace));
}
}