Skip to content

Commit b8116ac

Browse files
committed
Добавлен пример TCP клиента на Lwt
1 parent 81a7704 commit b8116ac

File tree

3 files changed

+61
-1
lines changed

3 files changed

+61
-1
lines changed

docs/.vitepress/config.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ export default defineConfig({
2323
base: "/in-examples/",
2424
link: "/index",
2525
items: [
26-
{ text: "Работа с JSON", link: "/json" },
26+
{ text: "JSON", link: "/json" },
27+
{ text: "TCP/IP", link: "/tcp-ip" },
2728
]
2829
},
2930
{

docs/in-examples/json.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Работы с JSON
2+
3+
TODO!

docs/in-examples/tcp-ip.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
---
2+
outline: deep
3+
---
4+
5+
# Работа с TCP/IP
6+
7+
В этой главе приведены примеры по работе с сетевыми протоколами.
8+
9+
> [!INFO] Смотрите также
10+
> - [Unix system programming in OCaml](https://ocaml.github.io/ocamlunix/) — детальная книга по системному программированию
11+
12+
## С помощью [Lwt_unix](../libraries/concurrency/lwt.md)
13+
14+
> [!INFO] Смотрите также
15+
> - [Освобождение ресурсов](../recipes/dispose-resources.md) — при работе с ресурсами очень важно правильно их освобождать,обязательна к ознакомлению;
16+
17+
### TCP клинт
18+
19+
```ocaml
20+
type tcp_connection = { ic : Lwt_io.input_channel; oc : Lwt_io.output_channel }
21+
22+
let create_tcp_connection ~host ~port =
23+
let open Unix in
24+
25+
(* Создание "сырого" Unix-сокет. *)
26+
let socket_fd = Lwt_unix.socket PF_INET SOCK_STREAM 0 in
27+
28+
(* Создание TCP-соединения по указному адресу. *)
29+
let address = ADDR_INET (inet_addr_of_string host, port) in
30+
Lwt_unix.connect socket_fd address;%lwt
31+
32+
(* Оборачивание сокета в удобную абстракцию каналов. *)
33+
let ic = Lwt_io.of_fd ~mode:Lwt_io.Input socket_fd in
34+
let oc = Lwt_io.of_fd ~mode:Lwt_io.Output socket_fd in
35+
36+
Lwt.return { ic; oc }
37+
38+
(* Для закрытия сокета достаточно закрыть один из каналов. *)
39+
let close { ic; _ } = Lwt_io.close ic
40+
```
41+
42+
```ocaml
43+
open Lwt.Infix
44+
45+
let () =
46+
Lwt_main.run @@
47+
let%lwt connection = create_tcp_connection ~host:"127.0.0.1" ~port:8080 in
48+
49+
(* Чтение и вывод считанной строки в stdout. *)
50+
Lwt_io.read_line connection.ic >>= Lwt_io.printl;%lwt
51+
52+
close connection
53+
```
54+
55+
> [!NOTE] В реальных проектах
56+
> - [Nats_lwt.Connection](https://github.com/romanchechyotkin/nats.ocaml/blob/main/lwt/connection.ml) — реализация подключения к NATS серверу;

0 commit comments

Comments
 (0)