[英]C# Async socket server receives only one message from client
我是套接字編程的新手。 我希望這個問題可以理解。
問題是,當我使用客戶端的button1_click
發送textbox
的內容時,服務器只會收到第一條消息。 我不知道怎么回事。
可能是什么問題?
這是服務器:
public partial class Form1 : Form
{
Socket server;
byte[] byteData = new byte[1024];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 20000);
server.Bind(endPoint);
server.Listen(1);
server.BeginAccept(new AsyncCallback(Accept), null);
textBox1.Text = "Server started...";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Accept(IAsyncResult ar)
{
try
{
Socket client = server.EndAccept(ar);
server.BeginAccept(new AsyncCallback(Accept), null);
client.BeginReceive(byteData, 0, byteData.Length,
SocketFlags.None, new AsyncCallback(Receive), client);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Receive(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
client.EndReceive(ar);
textBox1.Invoke(new Action(delegate ()
{
textBox1.AppendText(Environment.NewLine
+ Encoding.ASCII.GetString(byteData));
}));
byteData = null;
}
}
這是客戶:
public partial class Form1 : Form
{
Socket client;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == null)
button1.Enabled = false;
else
button1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEndPoint = new IPEndPoint(ip, 20000);
client.Connect(ipEndPoint);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
byte[] byteData = Encoding.ASCII.GetBytes(textBox1.Text);
client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(Send), null);
textBox1.Text = String.Empty;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Send(IAsyncResult ar)
{
try
{
client.EndSend(ar);
}
catch (ObjectDisposedException)
{ }
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
在Async
,無論何時您想聽消息,都BeginReceive
在服務器端重新初始化BeginReceive
。
因此,在Receive
回調中,應在BeginReceive
之后重新初始化EndReceive
。 否則,您將無法獲得下一條消息:
private void Receive(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
client.EndReceive(ar);
client.BeginReceive(byteData, 0, byteData.Length, //add BeginReceive again
SocketFlags.None, new AsyncCallback(Receive), client);
textBox1.Invoke(new Action(delegate ()
{
textBox1.AppendText(Environment.NewLine
+ Encoding.ASCII.GetString(byteData));
}));
byteData = null;
}
有關Async
更多工作示例,請查看以下內容: 使用套接字從服務器向客戶端發送值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.