110,552
社区成员
发帖
与我相关
我的任务
分享
/// 发送数据
public void Send(Socket handler, byte[] data)
{
StateObject obj = new StateObject();
obj.workSocket = handler;
obj.senddatalength = 0; //用来记录已发送多少数据,主要是为了知道发送进度。
obj.senddata = data ; //这句肯定是占内存的大头,可是如果不把要发送的数据储存在这,发送回调里怎么知道接下来应该发送哪一段数据呢?
int len = bufferlength;
if (obj.senddata.Length< StateObject.BufferSize)
{
len = obj.senddata.Length;
}
handler.BeginSend(obj.senddata, 0, len, 0,
new AsyncCallback(SendCallback), obj);
}
/// 发送回调
private void SendCallback(IAsyncResult ar)
{
StateObject obj = (StateObject)ar.AsyncState;
int bytesSent = obj.workSocket.EndSend(ar);
obj.senddatalength = obj.senddatalength + bytesSent;
if (bytesSent == 0)
{
if (sendcompleted != null)
{
sendcompleted();
}
obj.workSocket.Shutdown(SocketShutdown.Both);
obj.workSocket.Close();
}
else
{
if (sddata != null)
{
sddata(obj.senddatalength);
}
int sendlength = bufferlength;
if (obj.senddatalength + bufferlength > obj.senddata.Length)
{
sendlength = obj.senddata.Length - obj.senddatalength;
}
obj.workSocket.BeginSend(obj.senddata, obj.senddatalength, sendlength, 0,
new AsyncCallback(SendCallback), obj); //通过senddatalength来确定这次发送哪段数据
}
}
///接收回调
public void readCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead;
try
{
bytesRead = handler.EndReceive(ar);
}
catch (Exception)
{
return;
}
if (bytesRead > 0)
{
byte[] tempbt = new byte[bytesRead];
Array.Copy(state.buffer, 0, tempbt, 0, bytesRead);
state.data.AddRange(tempbt); //state.data是arraylist 用来储存已经接收到的数据
if (rcdata != null)
{
rcdata(state.data.Count); //事件 报告已接收多少数据
}
state.buffer = new Byte[bytesRead];
state.workSocket.BeginReceive(state.buffer, 0, bytesRead, 0,
new AsyncCallback(readCallback), state);
}
else
{
state.workSocket.Shutdown(SocketShutdown.Both);
state.workSocket.Close();
if (receivecompleted!=null)
{
receivecompleted(state);
}
}
}