Socket клиент сервер python

Socket Programming in Python: Client, Server, and Peer-to-Peer libraries

In this tutorial, you’ll learn how to exchange data between a client and a server using Python socket programming and the Socket API. Later, this tutorial will discuss exchanging data directly between two or more Python clients using a hosted provider. The source code used in this tutorial can be found within the GitHub repository. Socket programming connects two sockets (a client socket and a server socket) and allows them to communicate bi-directionally in real-time. Direct socket connections can benefit all real-time applications since data can be sent or received anytime.

Environment Set up

You will need a stable version of Python version 3.x installed on your machine. If you are a Windows user, you have the option of adding Python to your PATH. You will also need a code editor to follow along with this tutorial. Visual Studio Code is a popular open-source and free code editor that supports many languages and frameworks, including Python. VSCode also supports extensions for Python to help with code completion and debugging.

Build and run a Python socket application

Python socket stack

Let’s build a straightforward socket application using Python. Python provides a native socket class (socket module), so developers don’t need to depend on external libraries. Begin by setting up the Python socket client and server: Create the file client.py in the project directory. To use sockets, import the Python socket library and create a new socket object that connects to a specified IP address (in this case, localhost on port number 8080, but you can select any ipv4 address). Create a new connection to the socket server, send data to the TCP server, and close the socket connection. Your client.py file should look like this:

import socket client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('0.0.0.0', 8080)) client.send("I am CLIENT\n".encode()) from_server = client.recv(4096) client.close() print (from_server.decode()) 

You will need a socket server to listen for incoming connections and messages from your client. Create the file server.py and add the following contents:

import socket serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serv.bind(('0.0.0.0', 8080)) serv.listen(5) while True: conn, addr = serv.accept() from_client = '' while True: data = conn.recv(4096) if not data: break from_client += data.decode('utf8') print (from_client) conn.send("I am SERVER\n".encode()) conn.close() print ('client disconnected and shutdown') 

Server.py binds the socket object to the hostname (localhost) on port 8080 and continually listens for new client connections. When a client connects to this address, the server accepts the connection and reads any data. Once the data is successfully read from the client, the server provides a data response, at which point the client terminates the connection. To test this out yourself, open two terminal windows simultaneously. In one window, run:

Читайте также:  Php fetch one field

Python Socket Example

Notice that the server continues running and will establish a new connection every time you run the client and append any new output. The client will send the «I am CLIENT» string to the server and wait for a reply. The server will read the client’s message, output it to the terminal, and send back a response to the client.

Socket Programming in Python using PubNub

So far, this tutorial has covered exchanging messages between a server and a client, but what if you need to communicate directly between Python clients? Sending data directly between two or more client devices is tricky because you run into many scaling and security considerations as your number of devices increases. A client-server architecture is used to moderate and manage your client-to-client communication. If you don’t have a web server or you worry about your server scaling to meet your application’s demands, you should opt for a hosted, real-time communication solution such as PubNub. PubNub is a globally distributed and scalable cloud platform, so you don’t have to worry about deploying and maintaining servers. PubNub’s cross-platform SDKs, including Python, can identify users and send messages to specific channels, which only subscribed clients will receive.

Client-to-Client Python socket programming

So, how would the simple app presented previously be written with PubNub to exchange messages directly between two clients? It’s essential to understand that although PubNub uses the ‘publish’ and ‘subscribe’ architecture (pub/sub) to send and receive bidirectional messages between endpoints, it still uses sockets behind the scenes. PubNub gives you the benefits of socket communication without worrying about the details of Python network programming and maintaining an always-on connection between your clients regardless of the operating system. To integrate PubNub into the project, install the PubNub package with pip in the terminal; this will allow you to use the PubNub Python SDK and communicate with the PubNub infrastructure.

You will need to create two clients to connect to and communicate over the PubNub network. Create a file pn_client_1.py and add the following code:

from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub import time import os pnconfig = PNConfiguration() userId = os.path.basename(__file__) pnconfig.publish_key = 'demo' pnconfig.subscribe_key = 'demo' pnconfig.user_id = userId pnconfig.ssl = True pubnub = PubNub(pnconfig) def my_publish_callback(envelope, status): # Check whether request successfully completed or not if not status.is_error(): pass class MySubscribeCallback(SubscribeCallback): def presence(self, pubnub, presence): pass def status(self, pubnub, status): pass def message(self, pubnub, message): if message.publisher == userId : return print ("from device " + message.publisher + ": " + message.message) pubnub.add_listener(MySubscribeCallback()) pubnub.subscribe().channels("chan-1").execute() ## publish a message while True: msg = input("") if msg == 'exit': os._exit(1) pubnub.publish().channel("chan-1").message(str(msg)).pn_async(my_publish_callback) 

Create the file pn_client_2.py and add the same code as you used for pn_client_1.py The code above uses ‘demo’ keys, but you can obtain your custom PubNub keys for free. Run both pn_client_1.py and pn_client_2.py simultaneously in two different terminal windows

Источник

Сокеты в Python

Сегодня мы рассмотрим пример программирования сокетов Python. Мы создадим серверные и клиентские приложения на Python.

Программирование сокетов

Чтобы понять программирование сокетов Python, нам нужно знать о трех интересных темах – Socket Server, Socket Client и Socket.

Итак, что такое сервер? Сервер – это программное обеспечение, которое ожидает запросов клиентов и обслуживает или обрабатывает их соответственно.

С другой стороны, клиент запрашивает эту услугу. Клиентская программа запрашивает некоторые ресурсы к серверу, и сервер отвечает на этот запрос.

Socket – это конечная точка двунаправленного канала связи между сервером и клиентом. Сокеты могут обмениваться данными внутри процесса, между процессами на одной машине или между процессами на разных машинах. Для любого взаимодействия с удаленной программой мы должны подключаться через порт сокета.

Основная цель этого руководства по программированию сокетов – познакомить вас с тем, как сервер сокетов и клиент взаимодействуют друг с другом. Вы также узнаете, как написать программу сервера сокетов в Python.

Пример

Ранее мы говорили, что клиент сокета запрашивает некоторые ресурсы у сервера, и сервер отвечает на этот запрос.

Итак, мы разработаем и серверную, и клиентскую модель, чтобы каждый мог общаться с ними. Шаги можно рассматривать так:

  1. Программа сервера сокетов запускается сначала и ждет любого запроса.
  2. Клиентская программа сначала инициирует диалог.
  3. Затем серверная программа будет реагировать на запросы клиента соответственно.
  4. Клиентская программа будет завершена, если пользователь введет сообщение «до свидания». Серверная программа также завершится, когда завершится клиентская программа, это необязательно, и мы можем поддерживать выполнение серверной программы на неопределенный срок или завершить работу с помощью какой-либо конкретной команды в клиентском запросе.

Сервер сокетов

Мы сохраним программу сервера сокетов, как socket_server.py. Чтобы использовать соединение, нам нужно импортировать модуль сокета.

Затем последовательно нам нужно выполнить некоторую задачу, чтобы установить соединение между сервером и клиентом.

Мы можем получить адрес хоста с помощью функции socket.gethostname(). Рекомендуется использовать адрес порта пользователя выше 1024, поскольку номер порта меньше 1024 зарезервирован для стандартного интернет-протокола.

Смотрите приведенный ниже пример кода сервера:

import socket def server_program(): # get the hostname host = socket.gethostname() port = 5000 # initiate port no above 1024 server_socket = socket.socket() # get instance # look closely. The bind() function takes tuple as argument server_socket.bind((host, port)) # bind host address and port together # configure how many client the server can listen simultaneously server_socket.listen(2) conn, address = server_socket.accept() # accept new connection print("Connection from: " + str(address)) while True: # receive data stream. it won't accept data packet greater than 1024 bytes data = conn.recv(1024).decode() if not data: # if data is not received break break print("from connected user: " + str(data)) data = input(' -> ') conn.send(data.encode()) # send data to the client conn.close() # close the connection if __name__ == '__main__': server_program()

Итак, наш сервер сокетов работает на порту 5000 и будет ждать запроса клиента. Если вы хотите, чтобы сервер не завершал работу при закрытии клиентского соединения, просто удалите условие if и оператор break. Цикл while используется для бесконечного запуска серверной программы и ожидания клиентского запроса.

Клиент сокета

Мы сохраним клиентскую программу сокета python как socket_client.py. Эта программа похожа на серверную, за исключением привязки.

Основное различие между серверной и клиентской программой состоит в том, что в серверной программе необходимо связать адрес хоста и адрес порта вместе.

Смотрите ниже пример кода клиента сокета:

import socket def client_program(): host = socket.gethostname() # as both code is running on same pc port = 5000 # socket server port number client_socket = socket.socket() # instantiate client_socket.connect((host, port)) # connect to the server message = input(" -> ") # take input while message.lower().strip() != 'bye': client_socket.send(message.encode()) # send message data = client_socket.recv(1024).decode() # receive response print('Received from server: ' + data) # show in terminal message = input(" -> ") # again take input client_socket.close() # close the connection if __name__ == '__main__': client_program()

Вывод

Чтобы увидеть результат, сначала запустите программу сервера сокетов. Затем запустите клиентскую программу. После этого напишите что-нибудь из клиентской программы. Затем снова напишите ответ от серверной программы.

Наконец, напишите «до свидания» из клиентской программы, чтобы завершить обе программы. Ниже короткое видео покажет, как это работало на моем тестовом прогоне примеров программ сервера сокетов и клиента.

python socket programming, python socket server

pankaj$ python3.6 socket_server.py Connection from: ('127.0.0.1', 57822) from connected user: Hi -> Hello from connected user: How are you? -> Good from connected user: Awesome! -> Ok then, bye! pankaj$
pankaj$ python3.6 socket_client.py -> Hi Received from server: Hello -> How are you? Received from server: Good -> Awesome! Received from server: Ok then, bye! -> Bye pankaj$

Обратите внимание, что сервер сокетов работает на порту 5000, но клиенту также требуется порт сокета для подключения к серверу. Этот порт назначается случайным образом при вызове клиентского соединения. В данном случае это 57822.

Источник

Оцените статью