Skip to content

Commit

Permalink
adds socket example.
Browse files Browse the repository at this point in the history
  • Loading branch information
vany0114 committed Jun 1, 2017
1 parent 88990d7 commit 2cef138
Show file tree
Hide file tree
Showing 6 changed files with 108 additions and 2 deletions.
Binary file modified src/.vs/SignalRCore_SqlDependency/v15/.suo
Binary file not shown.
58 changes: 58 additions & 0 deletions src/SignalRCore.Web/EndPoints/MessagesEndPoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
using Microsoft.AspNetCore.Sockets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SignalRCore.Web.EndPoints
{
public class MessagesEndPoint : EndPoint
{
public ConnectionList Connections { get; } = new ConnectionList();

public override async Task OnConnectedAsync(Connection connection)
{
Connections.Add(connection);
await Broadcast($"{connection.ConnectionId} connected ({connection.Metadata[ConnectionMetadataNames.Transport]})");

try
{
while (await connection.Transport.Input.WaitToReadAsync())
{
Message message;
if (connection.Transport.Input.TryRead(out message))
{
var text = Encoding.UTF8.GetString(message.Payload);
text = $"{connection.ConnectionId}: {text}";
await Broadcast(Encoding.UTF8.GetBytes(text), message.Type, message.EndOfMessage);
}
}
}
finally
{
Connections.Remove(connection);
await Broadcast($"{connection.ConnectionId} disconnected ({connection.Metadata[ConnectionMetadataNames.Transport]})");
}
}

private Task Broadcast(string text)
{
return Broadcast(Encoding.UTF8.GetBytes(text), MessageType.Text, endOfMessage: true);
}

private Task Broadcast(byte[] payload, MessageType format, bool endOfMessage)
{
var tasks = new List<Task>(Connections.Count);
foreach (var c in Connections)
{
tasks.Add(c.Transport.Output.WriteAsync(new Message(
payload,
format,
endOfMessage)));
}

return Task.WhenAll(tasks);
}
}
}
1 change: 1 addition & 0 deletions src/SignalRCore.Web/SignalRCore.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<Content Include="wwwroot\js\main.js" />
<Content Include="wwwroot\js\main.min.js" />
<Content Include="wwwroot\lib\signalr\signalr-client.js" />
<Content Include="wwwroot\sockets.html" />
</ItemGroup>

<ItemGroup>
Expand Down
9 changes: 8 additions & 1 deletion src/SignalRCore.Web/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using Microsoft.EntityFrameworkCore;
using SignalRCore.Web.Persistence;
using SignalRCore.Web.Extensions;
using SignalRCore.Web.EndPoints;

namespace SignalRCore.Web
{
Expand All @@ -38,12 +39,13 @@ public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSignalR();
services.AddEndPoint<MessagesEndPoint>();

// dependency injection
services.AddDbContextFactory<InventoryContext>(Configuration.GetConnectionString("DefaultConnection"));
services.AddScoped<IInventoryRepository, DatabaseRepository>();
services.AddSingleton<InventoryDatabaseSubscription, InventoryDatabaseSubscription>();
services.AddScoped<IHubContext<Inventory>, HubContext<Inventory>>();
services.AddScoped<IInventoryRepository, DatabaseRepository>();
//services.AddSingleton<IInventoryRepository, InMemoryInventoryRepository>();
}

Expand All @@ -66,6 +68,11 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
routes.MapHub<Inventory>("/inventory");
});

app.UseSockets(routes =>
{
routes.MapEndpoint<MessagesEndPoint>("/message");
});

app.UseMvc(routes =>
{
routes.MapRoute(
Expand Down
2 changes: 1 addition & 1 deletion src/SignalRCore.Web/gulpfile.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/// <binding BeforeBuild='default' />

/*
This file is the main entry point for defining Gulp tasks and using Gulp plugins.
Click here to learn more. https://go.microsoft.com/fwlink/?LinkId=518007
Expand Down
40 changes: 40 additions & 0 deletions src/SignalRCore.Web/wwwroot/sockets.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1 id="transportName">Websocket Transport</h1>
<form id="sendmessage">
<input type="text" id="data" />
<input type="submit" value="Send" />
</form>
<ul id="messages"></ul>
<script src="lib/signalr/signalr-client.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
let url = `http://${document.location.host}/message`
let connection = new signalR.Connection(url);

connection.onDataReceived = data => {
let child = document.createElement('li');
child.innerText = data;
document.getElementById('messages').appendChild(child);
};

document.getElementById('sendmessage').addEventListener('submit', event => {
let data = document.getElementById('data').value;
connection.send(data);
event.preventDefault();
});

connection.start(signalR.TransportType.WebSockets).then(() => {
console.log("Opened");
}, () => {
console.log("Error opening connection");
});
});
</script>
</body>
</html>

0 comments on commit 2cef138

Please sign in to comment.