Python - привязка и прослушивание с помощью сокетов

Опубликовано: 12 Апреля, 2022

Программирование сокетов - это способ соединения двух узлов в сети для связи друг с другом. Один сокет (узел) прослушивает определенный порт на IP, в то время как другой сокет обращается к другому, чтобы сформировать соединение. Сервер формирует сокет слушателя, в то время как клиент обращается к серверу.

Примечание. Для получения дополнительной информации см. Программирование сокетов в Python.

Связывание и прослушивание с помощью сокетов

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listen mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client.

Example

import socket
import sys
  
  
# specify Host and Port 
HOST = "" 
PORT = 5789
    
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   
try:
    # With the help of bind() function 
    # binding host and port
    soc.bind((HOST, PORT))
       
except socket.error as massage:
      
    # if any error occurs then with the 
    # help of sys.exit() exit from the program
    print("Bind failed. Error Code : " 
          + str(massage[0]) + " Message " 
          + massage[1])
    sys.exit()
      
# print if Socket binding operation completed    
print("Socket binding operation completed")
   
# With the help of listening () function
# starts listening
soc.listen(9)
   
conn, address = soc.accept()
# print the address of connection
print("Connected with " + address[0] + ":" 
      + str(address[1]))
  • First of all we import socket which is necessary.
  • Then we made a socket object and reserved a port on our pc.
  • After that we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer.
  • After that we put the server into listen mode. 9 here means that 9 connections are kept waiting if the server is busy and if a 10th socket tries to connect then the connection is refused.

Теперь нам нужно что-то, с чем может взаимодействовать сервер. Мы могли бы доказать серверу подобное, просто чтобы знать, что наш сервер работает. Введите эти команды в терминал:

# start the server
$ python server.py

Держите указанный выше терминал открытым, откройте другой терминал и введите:

 $ telnet localhost 12345

Выход:

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.