2023-06-18 19:12:58 +03:00
|
|
|
|
---
|
|
|
|
|
title: "🆕 Простой пример socket сервера и клиента на Linux"
|
|
|
|
|
date: 2023-06-18T19:12:32+03:00
|
|
|
|
|
draft: false
|
|
|
|
|
tags: [network, linux, tips]
|
|
|
|
|
---
|
|
|
|
|
|
2023-06-18 19:17:42 +03:00
|
|
|
|
## Метод № 1: С помощью nc (netcat)
|
2023-06-18 19:12:58 +03:00
|
|
|
|
|
|
|
|
|
**Сервер**
|
|
|
|
|
|
|
|
|
|
```sh
|
|
|
|
|
nc -l localhost 3000
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
**Клиент**
|
|
|
|
|
|
|
|
|
|
```sh
|
|
|
|
|
nc localhost 3000
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## Тоже самое, но на unixsocket
|
|
|
|
|
|
|
|
|
|
**Сервер**
|
|
|
|
|
|
|
|
|
|
```sh
|
|
|
|
|
nc -l -U ./a.sock
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
**Клиент**
|
|
|
|
|
|
|
|
|
|
```sh
|
|
|
|
|
nc -U ./a.sock
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## Бонус
|
|
|
|
|
|
|
|
|
|
Скрипт сервера, который отправляет текущую дату, если получает `d`
|
|
|
|
|
и закрывает соединение, если получает `q`.
|
|
|
|
|
|
|
|
|
|
```bash
|
|
|
|
|
#!/bin/bash
|
|
|
|
|
|
|
|
|
|
coproc nc -l localhost 3000
|
|
|
|
|
|
|
|
|
|
while read -r cmd; do
|
|
|
|
|
case $cmd in
|
|
|
|
|
d) date ;;
|
|
|
|
|
q) break ;;
|
|
|
|
|
*) echo 'What?'
|
|
|
|
|
esac
|
|
|
|
|
done <&"${COPROC[0]}" >&"${COPROC[1]}"
|
|
|
|
|
|
|
|
|
|
kill "$COPROC_PID"
|
|
|
|
|
```
|