forked from cyrilCodePro/WebsocketExample
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudentWebsocketHandler.cs
More file actions
57 lines (41 loc) · 1.59 KB
/
Copy pathStudentWebsocketHandler.cs
File metadata and controls
57 lines (41 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using WebSocketExample.Context;
using WebSocketExample.Model;
namespace WebSocketExample.WebsocketService
{
public class StudentWebsocketHandler : WebSocketHandler
{
private readonly IServiceScopeFactory _service;
public StudentWebsocketHandler(WebSocketConnectionManager webSocketConnectionManager, IServiceScopeFactory service) : base(webSocketConnectionManager)
{
_service = service;
}
public override async Task ReceiveAsync(WebSocket socket, WebSocketReceiveResult result, byte[] buffer)
{
Student data = JsonConvert.DeserializeObject<Student>(Encoding.UTF8.GetString(buffer, 0, result.Count));
var responseObject = await GetResponseObjectAsync(data);
await SendMessageToAllAsync(
responseObject
);
}
private async Task<JObject> GetResponseObjectAsync(Student payload)
{
using (var scope = _service.CreateScope())
{
var _Context = scope.ServiceProvider.GetService<SocketExampleContext>();
await _Context.Student.AddAsync(payload);
var list = await _Context.Student.ToListAsync();
return JObject.FromObject(list);
}
}
}
}