Skip to content

Instantly share code, notes, and snippets.

@sembug
Last active February 27, 2020 13:55
Show Gist options
  • Select an option

  • Save sembug/682256765bdeae8e82e4093df2dfb413 to your computer and use it in GitHub Desktop.

Select an option

Save sembug/682256765bdeae8e82e4093df2dfb413 to your computer and use it in GitHub Desktop.
AngularWebSocket
import { Component, OnInit } from '@angular/core';
import { NamesService } from './services/names.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'ngWebSocket';
list: string[] = [];
constructor(private service: NamesService) { }
ngOnInit() {
this.service.commands$.subscribe(c => this.handleCommand(c));
}
ngOnDestroy() {
this.service.commands$.unsubscribe();
}
private add(list: string[], name: string) {
return list.concat(name);
}
private handleCommand(name: string) {
console.log(name);
this.list = this.add(this.list, name);
}
}
import { OnDestroy, Injectable } from '@angular/core';
import { webSocket, WebSocketSubject } from "rxjs/webSocket";
@Injectable({
providedIn: 'root',
})
export class NamesService implements OnDestroy {
private _commands$: WebSocketSubject<any>;
constructor() {
this._commands$ = webSocket('ws://localhost:8088');
}
ngOnDestroy() {
this._commands$.unsubscribe();
}
get commands$() {
return this._commands$;
}
}
using SuperWebSocket;
using System;
using System.Threading;
namespace ConsoleWebSocket
{
public class Program
{
private static WebSocketServer webSocketServer;
public static void Main(string[] args)
{
webSocketServer = new WebSocketServer();
int port = 8088;
webSocketServer.Setup(port);
webSocketServer.NewSessionConnected += WebSocketServer_NewSessionConnected;
webSocketServer.SessionClosed += WebSocketServer_SessionClosed;
webSocketServer.Start();
Console.WriteLine($"Server started @{port}.");
Console.ReadKey();
Console.WriteLine($"Server stopped.");
}
private static void WebSocketServer_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
{
Console.WriteLine($"Session closed.");
}
private static void WebSocketServer_NewSessionConnected(WebSocketSession session)
{
Console.WriteLine($"Session started: {session.CurrentToken}.");
while(session.Connected)
{
session.Send("{\"time\" : \"" + DateTime.Now.ToLongTimeString() + "\"}");
Thread.Sleep(5000);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment