37 lines
1.5 KiB
C#
37 lines
1.5 KiB
C#
|
using Fleck;
|
||
|
using Microsoft.Extensions.Logging;
|
||
|
using SharpChat.Connections;
|
||
|
using SharpChat.SockChat;
|
||
|
using System.Net;
|
||
|
|
||
|
namespace SharpChat;
|
||
|
|
||
|
public class SockChatConnection(IWebSocketConnection sock, IPEndPoint remoteEndPoint, ILogger logger) : Connection {
|
||
|
public IWebSocketConnection Socket { get; } = sock;
|
||
|
public IPEndPoint RemoteEndPoint { get; } = remoteEndPoint;
|
||
|
public ILogger Logger { get; } = logger;
|
||
|
|
||
|
public async Task Send(S2CPacket packet) {
|
||
|
if(!Socket.IsAvailable)
|
||
|
return;
|
||
|
|
||
|
string data = packet.Pack();
|
||
|
if(!string.IsNullOrWhiteSpace(data))
|
||
|
await Socket.Send(data);
|
||
|
}
|
||
|
|
||
|
public void Close(ConnectionCloseReason reason = ConnectionCloseReason.Unexpected) {
|
||
|
Socket.Close(reason switch {
|
||
|
ConnectionCloseReason.ShuttingDown => WebSocketCloseCode.GoingAway,
|
||
|
ConnectionCloseReason.Error => WebSocketCloseCode.InternalError,
|
||
|
ConnectionCloseReason.Restarting => WebSocketCloseCode.ServiceRestart,
|
||
|
ConnectionCloseReason.Unavailable => WebSocketCloseCode.ServiceRestart,
|
||
|
ConnectionCloseReason.Unauthorized => WebSocketCloseCode.Unauthorized,
|
||
|
ConnectionCloseReason.TimeOut => WebSocketCloseCode.Timeout,
|
||
|
ConnectionCloseReason.AccessDenied => WebSocketCloseCode.Forbidden,
|
||
|
ConnectionCloseReason.TooManyConnections => WebSocketCloseCode.TryAgainLater,
|
||
|
_ => WebSocketCloseCode.NormalClosure,
|
||
|
});
|
||
|
}
|
||
|
}
|