public class SocketConnection : IDisposable
{
public Byte[] msgBuffer = new byte[1048576];
private Socket _clientSocket = null;
public Socket ClientSocket
{
get { return this._clientSocket; }
}
public byte[] ReceivedBytes = null;
#region 构造
public SocketConnection(Socket sock)
{
this._clientSocket = sock;
}
#endregion
#region 连接
public void Connect(IPAddress ip, int port)
{
this.ClientSocket.BeginConnect(ip, port, ConnectCallback, this.ClientSocket);
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket socket = (Socket)ar.AsyncState;
if (socket != null && socket.Connected)
{
socket.EndConnect(ar);
}
}
catch (SocketException ex)
{
}
}
#endregion
#region 发送数据
public void Send(string data)
{
Send(System.Text.Encoding.Default.GetBytes(data));
}
private void Send(byte[] byteData)
{
try
{
this.ClientSocket.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), this.ClientSocket);
}
catch (SocketException ex)
{
}
}
private void SendCallback(IAsyncResult ar)
{
try
{
Socket socket = (Socket)ar.AsyncState;
if (socket != null && socket.Connected)//这时的socket有可能已经被关闭,资源被释放掉了
{
socket.EndSend(ar);
}
}
catch (SocketException ex)
{
}
}
#endregion
#region 接收数据
public void ReceiveData()
{
_clientSocket.BeginReceive(msgBuffer, 0, msgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
ReceivedBytes = null;
int receivedByteCount = _clientSocket.EndReceive(ar);
if (receivedByteCount > 0)
{
ReceivedBytes = new byte[receivedByteCount];
Array.Copy(msgBuffer, 0, ReceivedBytes, 0, receivedByteCount);
}
else
{
Dispose();
}
}
catch (SocketException ex)
{
}
}
public void Dispose()
{
try
{
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
}
catch (Exception ex)
{
}
}
#endregion
}
Socket 实现不同计算机之间通讯,发送/接收消息
最新推荐文章于 2023-01-03 10:29:38 发布