I currently build application for study Web API in ASP Net Core 7. So, I want to update automatically 2 values x and y by Web Socket. Here the API Quote Controller :
[HttpGet("ws")]
public async Task GetRealTimeQuote(int page=1,int limit = 10,string sector = "",string industry = "")
{
if (HttpContext.WebSockets.IsWebSocketRequest)
{
using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();
var random = new Random();
while (webSocket.State == WebSocketState.Open)
{
int x = random.Next(1, 100);
int y = random.Next(1, 100);
var buffer = Encoding.UTF8.GetBytes($"{{ "x": {x}, "y": {y} }}");
await webSocket.SendAsync(
new ArraySegment<byte>(buffer),
WebSocketMessageType.Text, true, CancellationToken.None);
await Task.Delay(2000); //
}
}
else
{
HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
}
}
The html file :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>WebSocket Test</title>
</head>
<body>
<script>
const socket = new WebSocket(`wss://localhost:7154/api/Quote/ws`);
socket.onopen = () => {
console.log('Connected to the server via WebSocket');
};
socket.onmessage = (event) => {
const quote = JSON.parse(event.data);
console.log('Received quote:', quote);
// Update the DOM with the received quote data
document.getElementById('x-value').textContent = `X: ${quote.x}`;
document.getElementById('y-value').textContent = `Y: ${quote.y}`;
};
socket.onclose = () => {
console.log('Connection closed');
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
</script>
<h1>Test WebSocket, Show x, y in Real-Time</h1>
<p id="x-value">X: </p>
<p id="y-value">Y: </p>
</body>
</html>
In Program.cs I already use
var webSocketOption = new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromMinutes(2)
};
app.UseWebSockets(webSocketOption);
The problem is the connection alway have error. I used dev tool in brower I saw
The localhost is correct. I still don’t know why the connection always fail. Or is it because I left the file in the wrong folder. Here where I put the html file path. Or the way I open it is wrong way (Whenever I run the project, I go to the project folder and click on the HTML file, Is this causes the HTML file to be unable to connect to the WebSocket ?). I working on this error all day so I really need your guys help