我使用以下代码创建了一个基本的自主式SignalR服务器:
class Program
{
static void Main(string[] args)
{
// This will *ONLY* bind to localhost, if you want to bind to all addresses
// use http://*:8080 to bind to all addresses.
// See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
// for more information.
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
取自:https://docs.microsoft.com/en-us/aspnet/signalr/overview/deployment/tutorial-signalr-self-host,适用于Javascript客户端。
我现在正在尝试创建一个Java客户端并获得以下代码,这些代码应该只是向服务器发送消息:
String host = "http://localhost:8080";
HubConnection connection = new HubConnection(host);
HubProxy proxy = connection.createHubProxy("MyHub");
connection.start();
try {
System.out.println("Sendng message...");
proxy.invoke( "Send", "Client", "Hello world!" ).get();
System.out.println("Message sent!");
} catch (InterruptedException e) {
System.out.println("err1");
// Handle ...
} catch (ExecutionException e) {
System.out.println("err2");
// Handle ...
}
我遇到的问题是服务器没有收到消息,似乎代码卡在调用调用中并且不打印Hello world!
消息。有人知道我做错了吗?
答案 0 :(得分:0)
hubProxy.invoke("sendMessageByUser", Message, WebApiToken).done(new Action<Void>() {
@Override
public void run(Void aVoid) {
if (aVoid != null)
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MyApplicationService.this, "Mesaj gönderildi", Toast.LENGTH_SHORT).show();
}
});
}
}).onError(new ErrorCallback() {
@Override
public void onError(final Throwable error) {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MyApplicationService.this.getApplicationContext(), "Bir hata oluştu" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
});