在客户端,我使用执行此方法的其他线程:
public void FillBuf(object sender)
{
var handler = (Socket)sender;
while (true)
{
received = 0;
while (received < 512)
{
int block = handler.Receive(bytes, received, bytes.Length - received, SocketFlags.None);
received += block;
}
que.Enqueue(bytes);
}
}
在服务器上我还有其他线程,我发送数据如下:
while(true)
{
for (int i=0; i < handler.Length; i++)
{
if (handler[i] != null)
{
bytes = BitConverter.GetBytes(move);//move
Array.Resize<byte>(ref bytes, 512);
handler[i].Send(bytes);
bytes = Transmition.SerializationCardArr(game.player[i].GetPlayerPack);//playerCards
Array.Resize<byte>(ref bytes, 512);
handler[i].Send(bytes);
bytes = Transmition.SerializationCardArr(table.GetAttackCards);//attackCards
Array.Resize<byte>(ref bytes, 512);
handler[i].Send(bytes);
bytes = Transmition.SerializationCardArr(table.GetDefendCards);//defendCards
Array.Resize<byte>(ref bytes, 512);
handler[i].Send(bytes);
}
}
}
当队列中的元素数量达到某个特定数量时,我从缓冲区中提取数据。
问题是缓冲区中的所有元素都是相同的。 谢谢。
答案 0 :(得分:2)
在您的客户端代码中,您反复使用相同的字节数组,然后将对它的引用排入队列。您需要为每个缓冲区创建 new 字节数组:
public void FillBuf(object sender)
{
var handler = (Socket)sender;
while (true)
{
// Note: use local variables here. You really don't want these variables
// getting mixed up between threads etc.
int received = 0;
byte[] bytes = new byte[512];
while (received < bytes.Length)
{
int block = handler.Receive(bytes, received, bytes.Length - received,
SocketFlags.None);
received += block;
}
que.Enqueue(bytes);
}
}