我正在研究 Windows Phone 中的 TCP 套接字。我创建了一个应用程序,我必须从服务器接收图像。为此,我将图像转换为字节数组以传输到 Windows Phone。
但是,有时windows phone 会得到整个字节数组,有时没有得到图像的整个字节数组。
所以,我在这里编码,
public void ReceiveMessage()
{
var responseListener = new SocketAsyncEventArgs();
responseListener.Completed += OnMessageReceivedFromServer;
var responseBuffer = new byte[bufferSize];
responseListener.SetBuffer(responseBuffer, 0, bufferSize);
connection.ReceiveAsync(responseListener);
}
收到消息后,我调用了 OnMessageReceivedFromServer。
在那里面
public void OnMessageReceivedFromServer(object sender, SocketAsyncEventArgs e)
{
// Convert the received message into a string
var message = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
//trailingmessage is the string declared with null.
//it will store the message if the message is greater than the bufferSize.
trailingMessage = trailingMessage + message;
//This checks wheather the message is remaining or not.
//if yes then it will again receives the message until it resumes.
if (e.BytesTransferred > 0 && e.BytesTransferred == bufferSize)
{
ReceiveMessage();
}
else
{
receivedstring = trailingMessage;
trailingMessage = null;
ReceiveMessage();
onMsg.Invoke(receivedstring);
}
}