以下是您可以使用的啓動代碼。
C#
//create an interface that contains definition of client side methods
public interface IClient
{
void messageReceived(string msg);
}
//create your Hub class that contains implementation of client methods
public class ChatHub : Hub<IClient>
{
public void sendMessage(string msg)
{
//log the incoming message here to confirm that its received
//send back same message with DateTime
Clients.All.messageReceived("Message received at: " + DateTime.Now.ToString());
}
}
HTML
添加引用的jQuery
script
文件和signalR
。
<script src="path/to/jquery.min.js"></script>
<script src="path/to/jquery.signalR.min.js"></script>
<!--this is the default path where SignalR generates its JS files so you don't need to change it.-->
<script src="~/signalr/hubs"></script>
JS
您需要安裝打字稿定義文件SignalR和jQuery。如果您使用的是TypeScript 2
,則在使用該文件時無需添加對index.d.ts
文件的引用。只需使用以下命令安裝類型。
npm install --save @types/jquery
npm install --save @types/signalr
與所有的設置完成後,你可以寫一個簡單TypeScript class
處理邏輯發送和接收消息。
export class MessageService {
//signalR connection reference
private connection: SignalR;
//signalR proxy reference
private proxy: SignalR.Hub.Proxy;
constructor() {
//initialize connection
this.connection = $.connection;
//to create proxy give your hub class name as parameter. IMPORTANT: notice that I followed camel casing in giving class name
this.proxy = $.connection.hub.createHubProxy('chatHub');
//define a callback method for proxy
this.proxy.on('messageReceived', (latestMsg) => this.onMessageReceived(latestMsg));
this.connection.hub.start();
}
private onMessageReceived(latestMsg: string) {
console.log('New message received: ' + latestMsg);
}
//method for sending message
broadcastMessage(msg: string) {
//invoke method by its name using proxy
this.proxy.invoke('sendMessage', msg);
}
}
我正在使用上面的代碼,顯然修改了我的需要,它工作正常。
你有沒有HUB的想法? – bilal
問題不在HUB ..正如我在我的問題中提到的「我已經安裝了SignalR的類型定義,但現在我不知道如何去實際使用SignalR,因爲當我輸入'$'或'jQuery'時我沒有被建議'.connections'例如「 –
//聲明代理引用集線器。 chat = $ .connection.YourHUBNAME;創建一個代理,你可以使用 – bilal