我刚刚开始测试信号器,我试图在我从HUB类获得响应后将文本添加到富文本框中,但它不起作用(我的richtextbox中没有显示文本)我不知道为什么...(代码运行没有错误)
//服务器
public class ConnectByHub : Hub
{
public void testFunc(mas) {
string ans = mas + " got it";
Clients.All.testFunc(ans);
} }
//客户端
private async void connectToServer()
{
Connection = new HubConnection(LocalClient);
HubProxy = Connection.CreateHubProxy("ConnectByHub");
try
{
await Connection.Start();
}
catch (Exception ex)
{
return;
}
string msg = "Hello friend!";
HubProxy.Invoke("testFunc", (msg)).Wait();
// Option one - doesn't work
HubProxy.On<string>("testFunc", (param) => Invoke((Action)(() => { MsgTxtBox.Text = "something happened"; })));
//Option two - doesn't work
HubProxy.On<string>("testFunc", (param) => this.Invoke((Action)(() => { MsgTxtBox.AppendText("Something happend " + Environment.NewLine); })));
}
答案 0 :(得分:0)
我认为部分问题是尝试从运行侦听器的同一Async方法(connectToServer)发送消息。
我大多使用了问题中的相同代码,但提出了几个问题:
public class ConnectByHub : Hub
{
public void Send(string message)
{
Clients.All.testFunc(message);
}
}
// Added button event
private void button1_Click(object sender, EventArgs e)
{
string msg = "Hello friend!";
HubProxy.Invoke("Send", msg).Wait();
}
private async void ConnectToServerAsync()
{
Connection = new HubConnection(LocalClient);
HubProxy = Connection.CreateHubProxy("ConnectByHub");
// Put the parmater in string.format()
HubProxy.On<string>("testFunc", (param) => this.Invoke((Action)(() => MsgTxtBox.AppendText(string.Format("{0}", param)))));
try
{
await Connection.Start();
}
catch (Exception ex)
{
richTextBox1.AppendText(string.Format("Unable to Connect to server ({0})", ServerURI));
return;
}
}