about summary refs log tree commit diff
path: root/Sample/Client.cs
diff options
context:
space:
mode:
authorBen Harris <ben@tilde.team>2020-04-22 11:42:09 -0400
committerBen Harris <ben@tilde.team>2020-04-22 11:42:09 -0400
commitca1518a9705ac289875c65c396a2ef7d219492d5 (patch)
tree1970852a07d58ae7c73fe869e91a425f265c641a /Sample/Client.cs
parent06a9882f65a6c2f7e72cc30340c28cf6bb76bcd1 (diff)
Add sample project
Diffstat (limited to 'Sample/Client.cs')
-rw-r--r--Sample/Client.cs68
1 files changed, 68 insertions, 0 deletions
diff --git a/Sample/Client.cs b/Sample/Client.cs
new file mode 100644
index 0000000..e9e286f
--- /dev/null
+++ b/Sample/Client.cs
@@ -0,0 +1,68 @@
+using System;
+using System.Collections.Generic;
+using System.Net.Sockets;
+using System.Text;
+using IrcTokens;
+
+namespace Sample
+{
+    public class Client
+    {
+        private readonly Socket _socket;
+        private readonly StatefulDecoder _decoder;
+        private readonly StatefulEncoder _encoder;
+        private readonly byte[] _bytes;
+
+        public Client()
+        {
+            _decoder = new StatefulDecoder();
+            _encoder = new StatefulEncoder();
+            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
+            _bytes = new byte[1024];
+        }
+
+        public void Start()
+        {
+            _socket.Connect("127.0.0.1", 6667);
+
+            Send(new Line {Command = "USER", Params = new List<string> {"username", "0", "*", "real name"}});
+            Send(new Line {Command = "NICK", Params = new List<string> {"statefulbot"}});
+
+            while (true)
+            {
+                var bytesReceived = _socket.Receive(_bytes);
+                var lines = _decoder.Push(_bytes);
+
+                if (lines.Count == 0)
+                {
+                    Console.WriteLine("! disconnected");
+                    _socket.Shutdown(SocketShutdown.Both);
+                    break;
+                }
+
+                foreach (var line in lines)
+                {
+                    Console.WriteLine($"< {line.Format()}");
+
+                    switch (line.Command)
+                    {
+                        case "PING":
+                            Send(new Line {Command = "PONG", Params = line.Params});
+                            break;
+                        case "001":
+                            Send(new Line {Command = "JOIN", Params = new List<string> {"#channel"}});
+                            break;
+                    }
+                }
+            }
+        }
+
+        private void Send(Line line)
+        {
+            Console.WriteLine($"> {line.Format()}");
+            _encoder.Push(line);
+            while (_encoder.PendingBytes.Length > 0)
+                _encoder.Pop(_socket.Send(_encoder.PendingBytes));
+        }
+    }
+}