我希望实现的功能是通过异步的方式将消息和文件发送给客户端。文件为xml、图片和视频类型。因为是刚开始学,有点没思路。要怎么样既能发消息又能发文件。现在我检测客户端和发消息的方式采用的是这篇文章介绍的方式(http://kb.cnblogs.com/a/1455703/)。但用这种方式来发送文件就遇到了点问题。
问题:1.收到的消息,就是byte[]的个数总是少。2.消息内,就是byte[]里出现乱码。这两个问题导致我接收的文件内容都是错的。
希望能指一下思路,帮我看看错哪了,谢谢。
这是发送的代码:
FileStream fs = new FileStream(System.Windows.Forms.Application.StartupPath + "\\ss.txt", FileMode.Open);
string strHead = "";
int totalLength = (int)fs.Length; //文件总长度
int packetsSize = 64 * 1024; //包的大小
int packetsNum = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(fs.Length) / Convert.ToDouble(packetsSize))); //包的数量
int currentLength = 0; //当前包的大小
strHead = "P" + (char)191 + "ss.txt" + (char)191 + totalLength + (char)191 + packetsSize + (char)191 + packetsNum + (char)191 + (totalLength - (packetsNum - 1) * packetsSize).ToString();
byte[] byteH = System.Text.Encoding.Unicode.GetBytes(strHead.ToCharArray(0, strHead.Length));
string strF = "<over>";
byte[] byteF = System.Text.Encoding.Unicode.GetBytes(strF.ToCharArray(0, strF.Length));
byte[] byteBuffer = null;
for (int i = 0; i < slist.Count; i++)
{
Socket s = (Socket)slist[i];
Send(s, byteH);
for (int j = 0; j < packetsNum; j++)
{
if (totalLength > packetsSize)
{
currentLength = packetsSize;
totalLength -= currentLength;
}
else
{
currentLength = totalLength;
}
byteBuffer = new byte[currentLength];
count = fs.Read(byteBuffer, 0, currentLength);
byte[] SendingBuffer = new byte[currentLength];
SendingBuffer = byteBuffer;
Send(s, SendingBuffer);
}
Send(s, byteF);//发送结束标志,但我总是受不到。
}
private void ReadCallback(IAsyncResult ai)
{
try
{
StateObject state = (StateObject)ai.AsyncState;
Socket client = state.workSocket;
int byteread = client.EndReceive(ai);
if (byteread > 0)
{
string ss=Encoding.UTF8.GetString(state.buffer, 0, byteread);
ss=ss.substing(0,6);
listbyte.Add(state.buffer);
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
if (ss=="<over>")
{
//收到结束标志后对文件和消息进行保存的处理
}
}
}
catch () { };
}
}