1 // =================================
 2 // Copyright (c) 2022 Seppo Laakko
 3 // Distributed under the MIT license
 4 // =================================
 5 
 6 using System.Os;
 7 
 8 namespace System
 9 {
10     public class Socket
11     {
12         public Socket(const string& nodeconst string& service) : socket(Connect(node.Chars()service.Chars()))
13         {
14         }
15         public ~Socket()
16         {
17             close(socket);
18         }
19         public void Send(const byte* bufferlong count)
20         {
21             long bytesWritten = Write(socketbuffercount);
22             count = count - bytesWritten;
23             while (count > 0)
24             {
25                 buffer = buffer + bytesWritten;
26                 bytesWritten = Write(socketbuffercount);
27                 count = count - bytesWritten;
28             }
29         }
30         public void Receive(byte* bufferlong count)
31         {
32             long bytesRead = Read(socketbuffercount);
33             count = count - bytesRead;
34             while (count > 0)
35             {
36                 buffer = buffer + bytesRead;
37                 bytesRead = Read(socketbuffercount);
38                 count = count - bytesRead;
39             }
40         }
41         public void Write(const string& str)
42         {
43             int count = cast<int>(str.Length());
44             UniquePtr<byte> mem(cast<byte*>(MemAlloc(count + 4)));
45             MemoryWriter writer(mem.Get()count + 4);
46             writer.Write(count);
47             for (int i = 0; i < count; ++i;)
48             {
49                 byte x = cast<byte>(str[i]);
50                 writer.Write(x);
51             }
52             Send(mem.Get()count + 4);
53         }
54         public string ReadStr()
55         {
56             byte[4] countBuf;
57             Receive(&countBuf[0]4);
58             MemoryReader reader(&countBuf[0]4);
59             int count = reader.ReadInt();
60             UniquePtr<byte> mem(cast<byte*>(MemAlloc(count)));
61             Receive(mem.Get()count);
62             string s;
63             for (int i = 0; i < count; ++i;)
64             {
65                 s.Append(cast<char>(mem.Get()[i]));
66             }
67             return s;
68         }
69         private int socket;
70     }
71 }