1
2
3
4
5
6 using System;
7 using System.IO;
8
9 namespace System.Net.Sockets
10 {
11 public class TcpListener : IOBase
12 {
13 public TcpListener(int port_) : socket(), port(port_)
14 {
15 auto result = socket.Bind(port);
16 if (result.Error())
17 {
18 SetErrorId(result.GetErrorId());
19 }
20 }
21 [nodiscard]
22 public Result<bool> Start()
23 {
24 if (Error())
25 {
26 return Result<bool>(ErrorId(GetErrorId()));
27 }
28 return Start(256);
29 }
30 [nodiscard]
31 public Result<bool> Start(int backlog)
32 {
33 if (Error())
34 {
35 return Result<bool>(ErrorId(GetErrorId()));
36 }
37 auto listenResult = socket.Listen(backlog);
38 if (listenResult.Error())
39 {
40 SetErrorId(listenResult.GetErrorId());
41 }
42 return listenResult;
43 }
44 [nodiscard]
45 public Result<bool> Stop()
46 {
47 if (Error())
48 {
49 return Result<bool>(ErrorId(GetErrorId()));
50 }
51 auto result = socket.Close();
52 if (result.Error())
53 {
54 SetErrorId(result.GetErrorId());
55 return Result<bool>(ErrorId(result.GetErrorId()));
56 }
57 socket = TcpSocket();
58 result = socket.Bind(port);
59 if (result.Error())
60 {
61 SetErrorId(result.GetErrorId());
62 return Result<bool>(ErrorId(result.GetErrorId()));
63 }
64 return result;
65 }
66 [nodiscard]
67 public Result<TcpSocket> AcceptSocket()
68 {
69 if (Error())
70 {
71 return Result<TcpSocket>(ErrorId(GetErrorId()));
72 }
73 auto result = socket.Accept();
74 if (result.Error())
75 {
76 SetErrorId(result.GetErrorId());
77 return Result<TcpSocket>(ErrorId(result.GetErrorId()));
78 }
79 return result;
80 }
81 public TcpSocket& Socket()
82 {
83 return socket;
84 }
85 private TcpSocket socket;
86 private int port;
87 }