Blog/content/posts/2023/linux/simple-socket-server-client.md
2023-06-18 19:17:42 +03:00

56 lines
881 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "🆕 Простой пример socket сервера и клиента на Linux"
date: 2023-06-18T19:12:32+03:00
draft: false
tags: [network, linux, tips]
---
## Метод № 1: С помощью nc (netcat)
**Сервер**
```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"
```