1
2
3
4
5
6 using System.Os;
7
8 namespace System
9 {
10 public class Socket
11 {
12 public Socket(const string& node, const string& service) : socket(Connect(node.Chars(), service.Chars()))
13 {
14 }
15 public ~Socket()
16 {
17 close(socket);
18 }
19 public void Send(const byte* buffer, long count)
20 {
21 long bytesWritten = Write(socket, buffer, count);
22 count = count - bytesWritten;
23 while (count > 0)
24 {
25 buffer = buffer + bytesWritten;
26 bytesWritten = Write(socket, buffer, count);
27 count = count - bytesWritten;
28 }
29 }
30 public void Receive(byte* buffer, long count)
31 {
32 long bytesRead = Read(socket, buffer, count);
33 count = count - bytesRead;
34 while (count > 0)
35 {
36 buffer = buffer + bytesRead;
37 bytesRead = Read(socket, buffer, count);
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 }