ircsharp/Examples/States/Client.cs

72 lines
2.2 KiB
C#
Raw Normal View History

2020-05-15 02:17:22 +00:00
using System;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
2020-05-15 03:06:10 +00:00
using IRCStates;
using IRCTokens;
2020-05-15 02:17:22 +00:00
2023-11-07 22:54:58 +00:00
namespace States;
internal class Client(string host, int port, string nick)
2020-05-15 02:17:22 +00:00
{
2023-11-07 22:54:58 +00:00
private readonly byte[] _bytes = new byte[1024];
private readonly StatefulEncoder _encoder = new();
private readonly Server _server = new("test");
private readonly Socket _socket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private void Send(string raw)
2020-05-15 02:17:22 +00:00
{
2023-11-07 22:54:58 +00:00
_encoder.Push(new(raw));
}
2020-05-15 02:17:22 +00:00
2023-11-07 22:54:58 +00:00
public void Start()
{
_socket.Connect(host, port);
while (!_socket.Connected) Thread.Sleep(1000);
2020-05-15 02:17:22 +00:00
2023-11-07 22:54:58 +00:00
Send("USER test 0 * test");
Send($"NICK {nick}");
2020-05-15 02:17:22 +00:00
2023-11-07 22:54:58 +00:00
while (true)
2020-05-15 02:17:22 +00:00
{
2024-03-26 20:10:54 +00:00
while (_encoder.PendingBytes.Length != 0)
2023-11-07 22:54:58 +00:00
{
foreach (var line in _encoder.Pop(_socket.Send(_encoder.PendingBytes)))
Console.WriteLine($"> {line.Format()}");
}
2020-05-15 02:17:22 +00:00
2023-11-07 22:54:58 +00:00
var bytesReceived = _socket.Receive(_bytes);
if (bytesReceived == 0)
2020-05-15 02:17:22 +00:00
{
2023-11-07 22:54:58 +00:00
Console.WriteLine("! disconnected");
_socket.Shutdown(SocketShutdown.Both);
_socket.Close();
break;
}
2020-05-15 02:17:22 +00:00
2023-11-07 22:54:58 +00:00
var receivedLines = _server.Receive(_bytes, bytesReceived);
foreach (var (line, _) in receivedLines)
{
Console.WriteLine($"< {line.Format()}");
2020-05-15 02:17:22 +00:00
2023-11-07 22:54:58 +00:00
switch (line.Command)
2020-05-15 02:17:22 +00:00
{
2023-11-07 22:54:58 +00:00
case Commands.Privmsg:
if (line.Params[1].Contains(_server.NickName))
Send($"PRIVMSG {line.Params[0]} :hi {line.Hostmask.NickName}!");
break;
case "PING":
Send($"PONG :{line.Params[0]}");
break;
case Numeric.RPL_WELCOME:
if (!_server.HasChannel("#irctokens")) Send("JOIN #irctokens");
break;
case "INVITE":
var c = line.Params[1];
if (!_server.HasChannel(c)) Send($"JOIN {c}");
break;
2020-05-15 02:17:22 +00:00
}
}
}
}
2023-11-07 22:54:58 +00:00
}