-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathTCPServer.cs
More file actions
77 lines (69 loc) · 2.93 KB
/
Copy pathTCPServer.cs
File metadata and controls
77 lines (69 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using System.Net;
using System.Net.Sockets;
using OneScript.Contexts;
using ScriptEngine.Machine;
using ScriptEngine.Machine.Contexts;
namespace OneScript.StandardLibrary.Net
{
/// <summary>
/// Простой однопоточный tcp-сокет. Слушает входящие соединения на определенном порту
/// </summary>
[ContextClass("TCPСервер", "TCPServer")]
public class TCPServer : AutoContext<TCPServer>
{
private readonly TcpListener _listener;
public TCPServer(int port)
{
_listener = new TcpListener(IPAddress.Any, port);
}
/// <summary>
/// Метод инициализирует TCP-сервер и подготавливает к приему входящих соединений
/// </summary>
[ContextMethod("Запустить", "Start")]
public void Start()
{
_listener.Start();
}
/// <summary>
/// Останавливает прослушивание порта.
/// </summary>
[ContextMethod("Остановить", "Stop")]
public void Stop()
{
_listener.Stop();
}
/// <summary>
/// Приостановить выполнение скрипта и ожидать соединений по сети.
/// После получения соединения выполнение продолжается
/// </summary>
/// <param name="timeout">Значение таймаута в миллисекундах.</param>
/// <returns>TCPСоединение. Объект, позволяющий обмениваться данными с удаленным хостом.</returns>
[ContextMethod("ОжидатьСоединения","WaitForConnection")]
public TCPClient WaitForConnection(int timeout = 0)
{
if (0 != timeout && !_listener.Pending())
{
System.Threading.Thread.Sleep(timeout);
if (!_listener.Pending())
return null;
}
var client = _listener.AcceptTcpClient();
return new TCPClient(client);
}
/// <summary>
/// Создает новый сокет с привязкой к порту.
/// </summary>
/// <param name="port">Порт, который требуется слушать.</param>
[ScriptConstructor]
public static TCPServer ConstructByPort(IValue port)
{
return new TCPServer((int)port.AsNumber());
}
}
}