Skip to content

Commit

Permalink
Fix: Long living sockets
Browse files Browse the repository at this point in the history
  • Loading branch information
NexusrexDev committed May 9, 2024
1 parent ee5d360 commit d2a524b
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions WebSocket/Socket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,42 @@

namespace ia_back.WebSocket
{
public class Socket
public class Socket
{

public System.Net.WebSockets.WebSocket socket;
public int id;

public Socket(int id)

Check warning on line 15 in WebSocket/Socket.cs

View workflow job for this annotation

GitHub Actions / build

Non-nullable field 'socket' must contain a non-null value when exiting constructor. Consider declaring the field as nullable.
{
this.id = id;
Console.WriteLine("Socket started with id: " + id);
}

public async Task Start(System.Net.WebSockets.WebSocket socket)
{
this.socket = socket;
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
id = int.Parse(message);
try
{
while (socket.State == WebSocketState.Open)
{
WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
SocketManager.Instance.RemoveSocket(this);
Console.WriteLine("Socket closed with id: " + id);
}
else
{
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
}
}
}
catch (WebSocketException)
{

}
}


}
}

0 comments on commit d2a524b

Please sign in to comment.