我最近使用CodeProject.com上找到的代码制作了此服务器和客户端。我可以将数据从客户端发送到服务器一次,但之后,我发送的数据都没有被确认。我需要在某个地方实现一个循环吗?代码如下:
string hi;
Socket sListener;
Socket handler;
Socket senderSocket;
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
IPHostEntry ipHost = Dns.GetHostEntry("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);
sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sListener.Bind(ipEndPoint);
sListener.Listen(10);
AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
sListener.BeginAccept(aCallback, sListener);
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);
Byte[] buffer = new Byte[1024];
handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), handler);
hi = Encoding.Unicode.GetString(buffer);
}
private void ReceiveCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
int endreceive = listener.EndReceive(ar);
}
private void button2_Click(object sender, EventArgs e)
{
IPHostEntry ipHost = Dns.GetHostEntry("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 4510);
senderSocket = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
senderSocket.Connect(ipEndPoint);
byte[] msg = Encoding.Unicode.GetBytes(textBox2.Text);
senderSocket.Send(msg);
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = hi;
}
private void button4_Click(object sender, EventArgs e)
{
byte[] msg = Encoding.Unicode.GetBytes("whatuphello");
senderSocket.Send(msg);
}
答案 0 :(得分:0)
使用async BeginReceive方法时,还应调用EndReceive。 以下是带有示例的类似问题的链接: C# Socket.BeginReceive/EndReceive