sharp-chat/SharpChat/ConnectionInfo.cs

65 lines
1.9 KiB
C#
Raw Normal View History

2022-08-30 15:00:58 +00:00
using Fleck;
using SharpChat.PacketsS2C;
2022-08-30 15:00:58 +00:00
using System;
using System.Net;
namespace SharpChat {
2024-05-20 16:16:32 +00:00
public class ConnectionInfo {
2023-02-16 21:25:41 +00:00
public IWebSocketConnection Socket { get; }
2024-05-20 16:16:32 +00:00
public DateTimeOffset LastPing { get; private set; }
2022-08-30 15:00:58 +00:00
2024-05-20 16:16:32 +00:00
public long UserId { get; private set; } = 0;
2024-05-20 16:16:32 +00:00
public string RemoteAddress { get; }
public ushort RemotePort { get; }
2024-05-20 16:16:32 +00:00
public string RemoteEndPoint { get; }
public ConnectionInfo(IWebSocketConnection sock) {
2023-02-16 21:25:41 +00:00
Socket = sock;
2024-05-20 16:16:32 +00:00
BumpPing();
2024-05-20 16:16:32 +00:00
IPAddress remoteAddr = IPAddress.Parse(sock.ConnectionInfo.ClientIpAddress);
if(IPAddress.IsLoopback(remoteAddr)
&& sock.ConnectionInfo.Headers.ContainsKey("X-Real-IP")
2024-05-10 19:18:55 +00:00
&& IPAddress.TryParse(sock.ConnectionInfo.Headers["X-Real-IP"], out IPAddress? realAddr))
2024-05-20 16:16:32 +00:00
remoteAddr = realAddr;
2024-05-20 16:16:32 +00:00
RemoteAddress = remoteAddr.ToString();
RemotePort = (ushort)sock.ConnectionInfo.ClientPort;
2024-05-20 16:16:32 +00:00
RemoteEndPoint = string.Format(
RemoteAddress.Contains(':') ? "[{0}]:{1}" : "{0}:{1}",
RemoteAddress, RemotePort
);
}
// please call this through ConnectionsContext
public void SetUserId(long userId) {
if(UserId > 0)
throw new InvalidOperationException("This connection is already associated with a user.");
UserId = userId;
2022-08-30 15:00:58 +00:00
}
public void Send(SockChatS2CPacket packet) {
2024-05-10 15:24:43 +00:00
string data = packet.Pack();
if(!string.IsNullOrWhiteSpace(data))
2024-05-20 16:24:14 +00:00
Send(data);
}
public void Send(string packet) {
if(Socket.IsAvailable)
Socket.Send(packet).Wait();
2022-08-30 15:00:58 +00:00
}
2023-02-07 15:01:56 +00:00
public void BumpPing() {
2024-05-20 16:16:32 +00:00
LastPing = DateTimeOffset.UtcNow;
2022-08-30 15:00:58 +00:00
}
2024-05-20 16:16:32 +00:00
public void Close(int code) {
Socket.Close(code);
}
2022-08-30 15:00:58 +00:00
}
}