using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using System.Net.Sockets;
using System.Net.NetworkInformation;
namespace ASP_NetWBsocket
{
public class Socket
{
private static string receivedMessage;
private static string sharedData = null; // Shared variable to store received data
{
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
{
return true;
};
{
try
{
// Connect to the WebSocket server
Console.WriteLine("Connecting to WebSocket server...");
webSocket.Options.SetRequestHeader("Authorization", "Bearer" + _authToken);
webSocket.Options.KeepAliveInterval = TimeSpan.FromMinutes(40);
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
Console.WriteLine("Connected!");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
{
var message = new StringBuilder();
byte[] buffer = new byte[4096 * 4];
{
WebSocketReceiveResult result;
{
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); /* comments - The process doesnt halt here its just that my dubugger comes out and im not able to see the message is next line wat is the reason , possibly connections is established or not I dont know cus i dont wat happened also the 2 time when i run the same process result variable populates and gives me the error for maximum connections and i if i dont abort the process if the message type is text when the the code iterates again through while it throws exception " System.Net.WebSockets.WebSocketException (0x83760002): Invalid data format for the specific protocol" */
var messageChunk = Encoding.UTF8.GetString(buffer, 0, result.Count);
message.Append(messageChunk);
} while (!result.EndOfMessage);
{
await
webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close response received",
CancellationToken.None);
}
else if (result.MessageType == WebSocketMessageType.Text && result.Count == 147)
{
webSocket.Abort();
receivedMessage = message.ToString();
sharedData = receivedMessage; // Store the received data in the shared variable
}
{
return sharedData; // Method to retrieve the shared data
}
}
}