我目前正在研究异步TCP程序,但我遇到了以下问题:
这真烦人,我不知道问题出在哪里。 这是我的客户代码:
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);
}
答案 0 :(得分:0)
我认为你有一些问题。一个似乎是stream
中的ReceiveCallback
。你从缓冲区得到一个字符串,然后不做任何事情。调整缓冲区大小,然后调整大小,如果恢复到原始大小似乎是浪费。可能会复制数据,然后调用GetString
,您可以单独留下缓冲区。
在您的服务器中,您致电BeginSend
发送_buffer,完成后,再次使用BeginSend
的二进制表示形式在SendingCallback
中再次呼叫tx1.Text
,但是您请勿拨打EndSend
,完成后请拨打EndSend
上的BeginSend
;但仍然没有把它称为第一。