R
R
Roma Kotolup2021-03-30 20:09:53
Python
Roma Kotolup, 2021-03-30 20:09:53

How to create a server in python socket?

How to create a server in python socket?
I need to create a variable that is visible to both computers with an API.
For example, a user received his API and gave another user his API.
And they take advantage of one change that they can see.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
german levi, 2021-03-30
@levi-german

import socket
import sys

# создаемTCP/IP сокет
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Привязываем сокет к порту
server_address = ('localhost', 10000)
print('Старт сервера на {} порт {}'.format(*server_address))
sock.bind(server_address)

# Слушаем входящие подключения
sock.listen(1)

while True:
    # ждем соединения
    print('Ожидание соединения...')
    connection, client_address = sock.accept()
    try:
        print('Подключено к:', client_address)
        # Принимаем данные порциями и ретранслируем их
        while True:
            data = connection.recv(16)
            print(f'Получено: {data.decode()}')
            if data:
                print('Обработка данных...')
                data = data.upper()
                print('Отправка обратно клиенту.')
                connection.sendall(data)
            else:
                print('Нет данных от:', client_address)
                break

    finally:
        # Очищаем соединение
        connection.close()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question