Hello everyone I want to how to listen to socket event with the event name in.net core and how to get data.
Loading
Hello everyone I want to how to listen to socket event with the event name in.net core and how to get data.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Vikas SinghPosted May 20, 2024, 11:52 AM
You can try with below:
1. Install the required package:
dotnet add package System.Net.WebSockets
2. Update your code to use WebSockets:
using System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
class Program
{
private static async Task StartListener()
{
HttpListener httpListener = new HttpListener();
httpListener.Prefixes.Add("http://localhost:11000/");
httpListener.Start();
Console.WriteLine("Waiting for a connection...");
while (true)
{
HttpListenerContext context = await httpListener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
Task.Run(() => HandleConnection(webSocketContext.WebSocket));
}
else
{
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
private static async Task HandleConnection(WebSocket webSocket)
{
byte[] buffer = new byte[1024];
WebSocketReceiveResult result = null;
try(buffer), CancellationToken.None);
{
while (webSocket.State == WebSocketState.Open)
{
result = await webSocket.ReceiveAsync(new ArraySegment
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
}
else
{
string receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine("Text received : {0}", receivedMessage);
string responseMessage = receivedMessage; // Echo back the same message(responseBuffer), WebSocketMessageType.Text, true, CancellationToken.None);
byte[] responseBuffer = Encoding.UTF8.GetBytes(responseMessage);
await webSocket.SendAsync(new ArraySegment
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
if (webSocket != null)
webSocket.Dispose();
}
}
public static void Main(string[] args)
{
Task listenerTask = StartListener();
Console.WriteLine("Press ENTER to exit...");
Connecting to the Server:Console.ReadLine();
}
}
Using a WebSocket client:
const socket = new WebSocket('ws://localhost:11000/');');
socket.onopen = function (event) {
socket.send('Hello Server!
};
socket.onmessage = function (event) {
console.log('Message from server: ', event.data);
};
This setup allows you to listen to WebSocket connections and handle incoming messages. The messages are echoed back to the client, and the connection remains open until explicitly closed by the client or server.
Vikas SinghPosted May 20, 2024, 11:44 AM
@Sunny, Ok let me explore if i got something then will post here.
Sourabh DhimanPosted May 20, 2024, 6:38 AM
@Vikas Singh I want to listen to this by socket URL.
Sourabh DhimanPosted May 20, 2024, 6:37 AM
The socket that has been created is in PHP using socket.io, and I need to listen to this socket in C#. Currently, there is no library like socket.io available in C#.
Vikas SinghPosted May 20, 2024, 6:02 AM
@Sunny, You can check below article to setup simple socket listener in .Net Core :
https://www.c-sharpcorner.com/article/building-a-simple-socket-listener-in-net-core/
Sam HobbsPosted May 19, 2024, 5:37 PM
Here are a couple more C# Corner articles that might help.
Using WebSocket To Build Real-Time Application Via ASP.NET Core
https://www.c-sharpcorner.com/article/using-websocket-to-build-real-time-application-via-asp-net-core
How To Use WebSockets In ASP.NET Core - Day Nine
https://www.c-sharpcorner.com/article/how-to-use-websockets-in-asp-net-core-day-nine2
The following is a Microsoft sample.
WebSocket sample - Code Samples | Microsoft Learn
https://learn.microsoft.com/en-us/samples/microsoft/windows-universal-samples/websocket
And the following is in GitHub; it appears to be quite useful.
WebSocket-Samples/HttpListenerWebSocketEcho/Client/Client.cs at master · paulbatum/WebSocket-Samples
https://github.com/paulbatum/WebSocket-Samples/blob/master/HttpListenerWebSocketEcho/Client/Client.cs
Jobin SPosted May 17, 2024, 6:18 AM
Hi Sunny,
You using .net core in signalR concepts
Refer this Article
https://www.c-sharpcorner.com/article/signalr-introduction-and-implementation-using-the-net-core-6-web-api-and-angula/