我在连接客户端时调用了此Server方法:
class Server {
protected override void clientIn(TcpClient client)//Called when a Client comes in
{
NetworkStream stream = client.GetStream();
byte[] y = new byte[client.ReceiveBufferSize];
objectState state = new objectState();
state.buffer = y;
state.user = client;
stream.BeginRead(y, 0, y.Length, read, state);
}
public void read(IAsyncResult ar)
{
Console.WriteLine("GetData");
objectState state = (objectState)ar.AsyncState;
byte[] buffer = state.buffer;
TcpClient client = state.user;
int byte=client.GetStream().EndRead(ar);
client.GetStream().BeginRead(buffer, 0, client.ReceiveBufferSize, read, state);
String text = Encoding.ASCII.GetString(buffer);
Console.WriteLine(text);
}
}
class objectState
{
public TcpClient user;
public byte[] buffer;
}
我从两个不同的客户端发送两个数据,我的问题是:
如果我不执行指令" Console.WriteLine(text);",在控制台中我得到2次消息" GetData"(这意味着我从2个客户端获取数据),
但如果我执行指令" Console.WriteLine(text);",在控制台中我得到1次消息" GetData"以及刚刚得到的数据。它是第一个客户的数据,第二个客户的数据丢失但我不明白为什么。
你能帮助我吗?
感谢您的时间
更新:
我以这种方式编辑了代码并且工作正常,但我不明白为什么:
protected override void clientIn(TcpClient client)
{
objectState state = new objectState();
state.user = client;
state.buffer= new byte[client.ReceiveBufferSize];
client.Client.BeginReceive(state.buffer, 0, client.ReceiveBufferSize, 0, new AsyncCallback(read), state);
}
public void read(IAsyncResult ar)
{
Console.WriteLine("GetData");
objectState state = (objectState)ar.AsyncState;
TcpClient client = stato.user;
int dataSize = client.Client.EndReceive(ar);
String data = "";
data = Encoding.ASCII.GetString(state.buffer, 0,dataSize);
Console.WriteLine("\n "+data);
client.Client.BeginReceive(stato.buffer, 0, client.ReceiveBufferSize, 0, new AsyncCallback(read), state);
}
我以前不明白哪里出错了。
更新2:
public void read(IAsyncResult ar)
{
Console.WriteLine("GetData");
objectState state = (objectState)ar.AsyncState;
byte[] buffer = state.buffer;
TcpClient client = state.user;
int dataSize=client.GetStream().EndRead(ar);
String text = Encoding.ASCII.GetString(buffer);
state.buffer = new byte[client.ReceiveBufferSize];//new buffer
client.GetStream().BeginRead(state.buffer, 0, client.ReceiveBufferSize, read, state);
Console.WriteLine(text);
}