C#socket接受二进制文件 如何知道已经全部接受完成了呢
云谣笑笑生 2012-10-28 10:57:02
class ClientState
{
public byte[] state = new byte[1024];
public Socket sk;
}
class FileState
{
public FileStream fs;
public string filename;
public const int length = 1024;
public byte[] state = new byte[length];
public Socket sk;
}
private void AsyCallback(IAsyncResult ar)
{
//获取侦听器
TcpListener tl = ar.AsyncState as TcpListener;
//获取客户端的Socket
sk = tl.EndAcceptSocket(ar);
ClientState cs = new ClientState();
cs.sk = sk;
sk.BeginReceive(cs.state, 0, cs.state.Length, SocketFlags.None, new AsyncCallback(Read_Callback), cs);
//异步接受数据
tl.BeginAcceptSocket(new AsyncCallback(AsyCallback), tl);
}
public void Read_Callback(IAsyncResult ar)
{
ClientState cs = (ClientState)ar.AsyncState;
Socket s = cs.sk;
int read = s.EndReceive(ar);
byte[] fnl = cs.state;
MemoryStream ms = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
ms.Write(fnl, 0, fnl.Length);
ms.Position = 0;
ArrayList aal = (ArrayList)bf.Deserialize(ms);
FileState fstate = new FileState();
fstate.filename = aal[1] as string;
fstate.sk = s;
fstate.fs = new FileStream(@"C:\Users\Administrator\" + fstate.filename, FileMode.OpenOrCreate, FileAccess.Write);
s.BeginReceive(fstate.state, 0, FileState.length, 0, new AsyncCallback(ReceMsgCallBack), fstate);
}
public void ReceMsgCallBack(IAsyncResult ar)
{
FileState cs = ar.AsyncState as FileState;
Socket thisSk = cs.sk;
int read = thisSk.EndReceive(ar);
if (read>0)
{
cs.fs.Write(cs.state, 0, read);
thisSk.BeginReceive(cs.state, 0, FileState.length, 0, new AsyncCallback(ReceMsgCallBack), cs);
}
else
{
cs.fs.Write(cs.state, 0, read);
ClientState tcs = new ClientState();
tcs.sk = thisSk;
cs.fs.Close();
sk.BeginReceive(tcs.state, 0, tcs.state.Length, SocketFlags.None, new AsyncCallback(Read_Callback), tcs);
}
}
经过修改该这是接受的代码 首先客户端先发送序列化的文件名过来 然后再发送文件过来 但我读取的时候 第一次接受个图片还可以 但第二次就不行了 不知道怎么回事 求大神求解