# Server

```python
"""Обязательные константы для работы сервера"""
SERVER_PORT = 64200 # Укажите свой, он должен быть свободным.
"""Неоязательные константы для работы сервера"""
BUFFER_SIZE = 1024 # Это значение по умолчанию.
```

{% hint style="danger" %}
Перед работой, обязательно установите`SERVER_PORT`, иначе сервер не будет работать.
{% endhint %}

{% hint style="info" %}
Для производительности, рекомендуем устанавливать buffer\_size равный весу передаваемых данных.
{% endhint %}

```python
def send(data: str) -> None:
```

<table><thead><tr><th width="133">Название</th><th width="125">Тип</th><th>Описание</th></tr></thead><tbody><tr><td>data</td><td>str</td><td>Информация для передачи</td></tr></tbody></table>

{% hint style="info" %}
По умолчанию, все аргументы установлены в соответствии с состоянием меню.
{% endhint %}

```python
def recv() -> str:
```

{% hint style="warning" %}
Пока не получит данные, заморозит текущий поток.
{% endhint %}

### close

```python
def close(self) -> None:
```

{% hint style="info" %}
Закрывает соединение с клиентом.
{% endhint %}

### Клиентский код для вашего приложения

**Python:**

```python
import socket

class Client:
    def __init__(self, host='127.0.0.1', port=65432):
        self.host = host
        self.port = port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((self.host, self.port))

    def send(self, data):
        self.s.sendall(data.encode('utf-8'))

    def recv(self, buffer_size=1024):
        data = self.s.recv(buffer_size)
        return data.decode('utf-8')

    def close(self):
        self.s.close()

if __name__ == "__main__":
    c = Client()
    c.send('hello napi') # Отправка данных в NAPI
    data = c.recv() # Получение данных от NAPI
    print(f"Получено от napi: {data}")
    c.close()
```

**C++:**

```cpp
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

class Client {
public:
    Client(std::string host = "127.0.0.1", int port = 65432) {
        this->host = host;
        this->port = port;

        // Создание сокета
        sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0) {
            perror("Ошибка создания сокета");
            exit(1);
        }

        // Установка адреса сервера
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(port);
        inet_pton(AF_INET, host.c_str(), &server_addr.sin_addr);

        // Подключение к серверу
        if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
            perror("Ошибка подключения");
            exit(2);
        }
    }

    void send(const std::string& data) {
        if (::send(sock, data.c_str(), data.length(), 0) < 0) {
            perror("Ошибка отправки данных");
        }
    }

    std::string recv(int buffer_size = 1024) {
        char buffer[buffer_size];
        std::memset(buffer, 0, buffer_size);
        ssize_t bytes_received = ::recv(sock, buffer, buffer_size, 0);
        if (bytes_received < 0) {
            perror("Ошибка получения данных");
            return "";
        }
        return std::string(buffer, bytes_received);
    }

    void close() {
        ::close(sock);
    }

private:
    int sock;
    std::string host;
    int port;
    struct sockaddr_in server_addr;
};

int main() {
    Client c;
    c.send("hello napi"); // Отправка данных в NAPI
    std::string data = c.recv(); // Получение данных от NAPI
    std::cout << "Получено от napi: " << data << std::endl;
    c.close();

    return 0;
}
```

**Lua:**

```lua
local socket = require("socket")

local host = "127.0.0.1"
local port = 65432
local tcp = assert(socket.tcp())

tcp:connect(host, port)

function send(tcp, data)
    tcp:send(data .. "\n")
end

function recv(tcp)
    local data, err = tcp:receive()
    if not err then
        return data
    else
        return nil, err
    end
end

function close(tcp)
    tcp:close()
end

-- Использование
send(tcp, "hello napi") -- Отправка данных в NAPI
local data, err = recv(tcp) -- Получение данных от NAPI
if data then
    print("Получено от napi: " .. data)
else
    print("Ошибка получения данных: " .. err)
end
close(tcp)
```

**Java:**

```java
import java.io.*;
import java.net.Socket;

public class Client {
    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;
    private final String host;
    private final int port;

    public Client(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void connect() throws IOException {
        socket = new Socket(host, port);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);
    }

    public void send(String data) {
        out.println(data);
    }

    public String recv() throws IOException {
        return in.readLine();
    }

    public void close() throws IOException {
        in.close();
        out.close();
        socket.close();
    }

    public static void main(String[] args) {
        Client client = new Client("127.0.0.1", 65432);
        try {
            client.connect();
            client.send("hello napi"); // Отправка данных в NAPI
            String data = client.recv(); // Получение данных от NAPI
            System.out.println("Получено от napi: " + data);
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.neuralaim.ru/napi/dokumentaciya-or-api/server.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
