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

How to send messages using Python Socket module?

WBOY
Release: 2023-05-08 13:40:16
forward
995 people have browsed it

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
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template