我目前正在異步TCP程序,但我有以下問題:TCP套接字:流發送/異步操作兩次接收
- - 當服務器發送一些數據流,客戶第一接收一個空的緩衝區,然後它接收流。
- - 在第一個流發送之後,如果我發送另一個流,則客戶端的緩衝區將包含發送的第一個流和當前的 流。
- - 如果我送另一個流,緩衝區將包含我發前的數據流和當前one..and等..
這實在是煩人,我不知道哪來的問題。 這是我的客戶端代碼:
Socket CLIENT;
byte[] _buffer;
private void button1_Click(object sender, EventArgs e)
{
Start();
}
void Start()
{
CLIENT = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
CLIENT.BeginConnect(IPAddress.Parse("the IPaddress"), 1234, new AsyncCallback(ConnectionCallBack), null);
}
private void ConnectionCallBack(IAsyncResult ar)
{
try
{
CLIENT.EndConnect(ar);
_buffer = new byte[CLIENT.ReceiveBufferSize];
CLIENT.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
}
catch (Exception Er)
{
MessageBox.Show("[[[[ERROR:1]]]]=>" + Er.Message);
}
}
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
int lenght = CLIENT.EndReceive(ar);
if (lenght == 0) { return; }
Array.Resize(ref _buffer, lenght);
string stream = ASCIIEncoding.ASCII.GetString(_buffer);
Array.Resize(ref _buffer, CLIENT.ReceiveBufferSize);
CLIENT.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), null);
}
catch (Exception ex) { MessageBox.Show("[[[[hoERROR:2]]]]=>" + ex.Message); }
}
這裏是服務器:
private void button2_Click(object sender, EventArgs e)
{
try
{
Socket socket = (Socket)listW.SelectedItems[0].Tag; //contains the socket
socket.BeginSend(_buffer,0,_buffer.Length,SocketFlags.None,new AsyncCallback(SendingCallBack),socket);
ServerSocket.BeginAccept(new AsyncCallback(AcceptCallBack),null);
}
catch (Exception er) { MessageBox.Show("[[[[ERROR:]]]]=>" + er.ToString()); }
}
private void SendingCallBack(IAsyncResult ar)
{
try
{
Socket socket = (Socket)ar.AsyncState;
_buffer = ASCIIEncoding.ASCII.GetBytes(tx1.Text);
socket.BeginSend(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(FinalCallBack),socket);
}
catch (Exception er) { MessageBox.Show("[[[[ERROR:3]]]]=>" + er.ToString()); }
}
private void Final(IAsyncResult ar)
{
Socket client = ar.AsyncState as Socket;
client.EndSend(ar);
}
我已經在GitHub上的一個項目,可以幫助你:https://github.com/Mellen/Networking-Samples – 2013-04-07 19:52:31
謝謝,但我需要明白什麼是錯誤的,我code.where是錯誤 – Leo 2013-04-07 19:53:51
我刪除了自己的新問題並且刪除了這一個,因爲刪除某人花時間回答的問題相當不敬,只是爲了讓您可以重新發布以獲得更多關注。請不要這樣做。 – 2013-04-08 19:52:37