Home  >  Article  >  Backend Development  >  How to send messages using Python Socket module?

How to send messages using Python Socket module?

WBOY
WBOYforward
2023-05-08 13:40:16901browse

1. The ports must be consistent.

2. Server IP. The server and client IP can also be the same.

3. Receive UDP datagrams from any sender on the given port.

4. Receive a 1024-byte datagram.

Example

# FileName: client.py
 
import socket
import pandas as pd
 
port = 8001  # 端口和上面一致
host = "localhost"  # 服务器IP,这里服务器和客户端IP同一个
 
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in range(10):
    sock.sendto(("Successful! Message %s! " % i).encode(), (host, port))
# FileName: service.py
def socket_service():
    port = 8001
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("", port))  # 从给定的端口,从任何发送者,接收UDP数据报
    print("Waiting for the port", port)
 
    while True:
        data, address = sock.recvfrom(1024)  # 接收一个报文为1024字节的数据报
        print("Received:", data.decode(), "from", address)
        if data.decode() == 'over':
            break

The above is the detailed content of How to send messages using Python Socket module?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete