gpt4 book ai didi

c# - 异步套接字调用卡住 UI 线程

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:15 26 4
gpt4 key购买 nike

我一直在开发客户端到服务器的聊天信使,但遇到了一些有关异步调用的问题。一段时间以来,我一直在尝试修复它们,但没有成功。

问题出在客户端,连接到服务器没有问题,但是一旦调用第一个“BeginSend”方法,整个客户端就会停止响应。(它不会 100% 停止,它偶尔会响应,但是在一个荒谬的响应之后30 秒以上的时间)。其余调用运行良好,但 UI 不会响应。服务器响应也很好。

这是代码,我在此处评论了客户端首先卡住的地方。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Net.Sockets;
using System.Net;

namespace Client_GUI_Design_Test
{
public partial class Login : Form
{
public Socket clientSocket;
public string strName;
public byte[] byteData = new byte[1024];
public List<String> contacts = new List<String>();
public Boolean needUpdate = true;
// public Panel globalPanel;
public Login()
{
InitializeComponent();
}

public struct Contact
{
public string strName;
}


public int num1 = 0;
public void addContact(String contactName, String message, int status, int imageNum)
{
//MessageBox.Show(this.Size.Width.ToString());
panel1.HorizontalScroll.Enabled = false;
panel1.HorizontalScroll.Visible = false;
if (num1 >= panel1.Size.Height - 47)
{
panel1.Size = new Size(257, 514);
this.Size = new Size(277, this.Size.Height);
panel1.AutoScroll = true;
panel1.HorizontalScroll.Enabled = false;
panel1.HorizontalScroll.Visible = false;
panel1.VerticalScroll.Visible = true;
}
panel1.VerticalScroll.Value = 0;
//Contact Panel
Panel contactPanel = new Panel();
contactPanel.Size = new Size(249, 47);
contactPanel.Margin = new System.Windows.Forms.Padding(0, 0, 0, 0);

//Name Label
Label name = new Label();
//Font
float size = 12.00f;
name.Font = new Font("Microsoft Sans Serif", size, FontStyle.Bold);
//Location
name.Location = new Point(29, 3);
//Size
name.Size = new Size(112, 20);
name.Text = contactName;
//Events
#region
name.MouseEnter += delegate
{
contactPanel.BackColor = Color.Gainsboro;
};
name.MouseLeave += delegate
{
contactPanel.BackColor = System.Drawing.SystemColors.Control;
};
#endregion
contactPanel.Controls.Add(name);

//Image Box
PictureBox image = new PictureBox();
//Image
image.Image = imageList1.Images[imageNum];
//Size
image.Size = new Size(56, 42);
//Location
image.Location = new Point(187, 4);
//Events
#region
image.MouseEnter += delegate
{
contactPanel.BackColor = Color.Gainsboro;
};
image.MouseLeave += delegate
{
contactPanel.BackColor = System.Drawing.SystemColors.Control;
};
#endregion
contactPanel.Controls.Add(image);

//Status
PictureBox statusPic = new PictureBox();
//Image
statusPic.Image = imageList2.Images[status];
//Size
statusPic.Size = new Size(20, 20);
//Location
statusPic.Location = new Point(3, 3);
//Events
#region
statusPic.MouseEnter += delegate
{
contactPanel.BackColor = Color.Gainsboro;
};
statusPic.MouseLeave += delegate
{
contactPanel.BackColor = System.Drawing.SystemColors.Control;
};
#endregion
contactPanel.Controls.Add(statusPic);

//Message Label
Label messageL = new Label();
//Font
float sizem = 11.25f;
messageL.Font = new Font("Microsoft Sans Serif", sizem, FontStyle.Bold);
messageL.ForeColor = Color.Gray;
//Location
messageL.Location = new Point(29, 23);
//Size
messageL.Size = new Size(153, 18);
//Text
messageL.Text = message;
//Events
#region
messageL.MouseEnter += delegate
{
contactPanel.BackColor = Color.Gainsboro;
};
messageL.MouseLeave += delegate
{
contactPanel.BackColor = System.Drawing.SystemColors.Control;
};
messageL.MouseHover += delegate
{
ToolTip tip = new ToolTip();
tip.Tag = messageL.Text;
tip.Show(messageL.Text, messageL, 1, 1, 750);
};
#endregion

contactPanel.Controls.Add(messageL);

contactPanel.Paint += new PaintEventHandler(contactPanel_Paint);
{


};
contactPanel.MouseEnter += delegate
{
contactPanel.BackColor = Color.Gainsboro;
};
contactPanel.MouseLeave += delegate
{
contactPanel.BackColor = System.Drawing.SystemColors.Control;
};
contactPanel.Location = new Point(0, num1);
//globalPanel = contactPanel;
//panel1.Controls.Add(contactPanel);
addPanel(contactPanel);
num1 += 47;


}

public delegate void UpdatePanelCallBack(Panel panel);
private void addPanel(Panel panel)
{
if (InvokeRequired)
{
object[] pList = { panel };
panel1.BeginInvoke(new
UpdatePanelCallBack(OnUpdatePanel), pList);
}

else
{
OnUpdatePanel(panel);
}
}

private void OnUpdatePanel(Panel panel)
{
panel1.Controls.Add(panel);
}

VisualStyleRenderer renderer = new VisualStyleRenderer(VisualStyleElement.Button.PushButton.Normal);
void contactPanel_Paint(object sender, PaintEventArgs e)
{
renderer.DrawEdge(e.Graphics, panel1.ClientRectangle,
Edges.Top,
EdgeStyle.Bump, EdgeEffects.Flat);
}

private void button3_Click(object sender, EventArgs e)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text);
//Server is listening on port 43594
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 43594);

//Connect to the server
clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclient", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


}

private void OnSend(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndSend(ar);
//clientSocket.EndSend(ar);
//strName = textBox2.Text;
// DialogResult = DialogResult.OK;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclient", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void OnConnect(IAsyncResult ar)
{
try
{
clientSocket.EndConnect(ar);

//We are connected so we login into the server
Data msgToSend = new Data();
msgToSend.cmdCommand = Command.Login;
msgToSend.strName = textBox2.Text;
msgToSend.strMessage = null;

byte[] b = msgToSend.ToByte();

//Send the message to the server
//HERE - Starts freezing the UI thread, continues to do background operations
clientSocket.BeginSend(b, 0, b.Length, SocketFlags.None, new AsyncCallback(OnSend), clientSocket);

clientSocket.BeginReceive(byteData,
0,
byteData.Length,
SocketFlags.None,
new AsyncCallback(OnReceive),
clientSocket);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclient", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

panel4.Visible = false;
panel1.Visible = true;
}

public void OnReceive(IAsyncResult ar)
{
try
{
clientSocket.EndReceive(ar);

Data msgReceived = new Data(byteData);
//Accordingly process the message received
switch (msgReceived.cmdCommand)
{
case Command.Login:
//lstChatters.Items.Add(msgReceived.strName);
break;

case Command.Logout:
//lstChatters.Items.Remove(msgReceived.strName);
break;

case Command.Message:
break;

case Command.List:
MessageBox.Show(msgReceived.strName);
//contacts.Add(msgReceived.strName);
needUpdate = true;
//lstChatters.Items.AddRange(msgReceived.strMessage.Split('*'));
//lstChatters.Items.RemoveAt(lstChatters.Items.Count - 1);
//txtChatBox.Text += "<<<" + strName + " has joined the room>>>\r\n";

break;
}

byteData = new byte[1024];

clientSocket.BeginReceive(byteData,
0,
byteData.Length,
SocketFlags.None,
new AsyncCallback(OnReceive),
clientSocket);

}
catch (ObjectDisposedException)
{ }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclientTCP: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

private void Login_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
//backgroundWorker1.RunWorkerAsync();

}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
if(needUpdate){

}
}
}


private void Login_DoubleClick(object sender, EventArgs e)
{
MessageBox.Show("");
foreach (string s in contacts)
{
addContact(s, "Random Message", 0, 1);
needUpdate = false;
}
}
}
}

修复了其他类中的问题,但在 OnReceive 中仍然存在问题(可能有助于更快地识别问题)

public void OnReceive(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndReceive(ar);

Data msgReceived = new Data(byteData);
//Accordingly process the message received
switch (msgReceived.cmdCommand)
{
case Command.Login:
//lstChatters.Items.Add(msgReceived.strName);
break;

case Command.Logout:
//lstChatters.Items.Remove(msgReceived.strName);
break;

case Command.Message:
break;

case Command.List:
MessageBox.Show(msgReceived.strName);
//contacts.Add(msgReceived.strName);
needUpdate = true;
//lstChatters.Items.AddRange(msgReceived.strMessage.Split('*'));
//lstChatters.Items.RemoveAt(lstChatters.Items.Count - 1);
//txtChatBox.Text += "<<<" + strName + " has joined the room>>>\r\n";

break;
}

byteData = new byte[1024];

/* client.BeginReceive(byteData,
0,
byteData.Length,
SocketFlags.None,
new AsyncCallback(OnReceive),
client);*/

}
catch (ObjectDisposedException)
{ }
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclientTCP: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

我知道这是很多代码,很抱歉,但这是我最后的选择,我完全被卡住了。任何帮助将不胜感激:)

最佳答案

您正在从不同的线程访问 clientSocket。

button3_Click 中调用 BeginConnect 像这样传递你的套接字:

//Connect to the server
clientSocket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), clientSocket);

OnReceive 中从 AsyncState 获取套接字(调用 BeginConnect 时传递到这里):

Socket client = (Socket)ar.AsyncState;
client.EndReceive(ar);

来自 msdn EndConnect

EndConnect是阻塞方法,完成BeginConnect方法中启动的异步远程主机连接请求

在调用 BeginConnect 之前,您需要创建一个实现 AsyncCallback 委托(delegate)的回调方法。此回调方法在单独的线程中执行,并在 BeginConnect 返回后由系统调用。回调方法必须接受 BeginConnect 方法返回的 IAsyncResult 作为参数。

编辑:

正如我在您的代码中看到的那样,您正在使用 byteData 缓冲区,它被声明为类字段并在 BeginReceive 尝试访问它时从另一个线程访问它。查看异步服务器套接字示例,了解如何处理读取部分。

您可以在 msdn Socket Code Examples 上查看此示例

Asynchronous Server Socket Example

Asynchronous Client Socket Example

关于c# - 异步套接字调用卡住 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22651746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com