64 lines
2 KiB
C#
64 lines
2 KiB
C#
using Fleck;
|
|
using SharpChat.SockChat.PacketsS2C;
|
|
using System;
|
|
using System.Net;
|
|
|
|
namespace SharpChat.SockChat {
|
|
public class SockChatConnectionInfo {
|
|
public IWebSocketConnection Socket { get; }
|
|
public DateTimeOffset LastPing { get; private set; }
|
|
|
|
public long UserId { get; private set; } = 0;
|
|
|
|
public string RemoteAddress { get; }
|
|
public ushort RemotePort { get; }
|
|
public string RemoteEndPoint { get; }
|
|
|
|
public SockChatConnectionInfo(IWebSocketConnection sock) {
|
|
Socket = sock;
|
|
|
|
BumpPing();
|
|
|
|
IPAddress remoteAddr = IPAddress.Parse(sock.ConnectionInfo.ClientIpAddress);
|
|
|
|
if(IPAddress.IsLoopback(remoteAddr)
|
|
&& sock.ConnectionInfo.Headers.ContainsKey("X-Real-IP")
|
|
&& IPAddress.TryParse(sock.ConnectionInfo.Headers["X-Real-IP"], out IPAddress? realAddr))
|
|
remoteAddr = realAddr;
|
|
|
|
RemoteAddress = remoteAddr.ToString();
|
|
RemotePort = (ushort)sock.ConnectionInfo.ClientPort;
|
|
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;
|
|
}
|
|
|
|
public void Send(SockChatS2CPacket packet) {
|
|
string data = packet.Pack();
|
|
if(!string.IsNullOrWhiteSpace(data))
|
|
Send(data);
|
|
}
|
|
|
|
public void Send(string packet) {
|
|
if(Socket.IsAvailable)
|
|
Socket.Send(packet).Wait();
|
|
}
|
|
|
|
public void BumpPing() {
|
|
LastPing = DateTimeOffset.UtcNow;
|
|
}
|
|
|
|
public void Close(int code) {
|
|
Socket.Close(code);
|
|
}
|
|
}
|
|
}
|