python—简单实现socket通信(TCP、UDP)

python—简单实现socket通信(TCP、UDP),第1张

python—简单实现socket通信(TCP、UDP) TCP 客户-服务器程序

服务端程序

// TCPServer.py

import socket

hostName = '127.0.0.1'
port = 9000
address = (hostName, port)  # 开放的地址和端口
# 1.创建socket对象,采用ipv4协议、流式数据传输(面向连接)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(address)  # 2.绑定地址与端口
server.listen(5)  # 3.设置监听数
print(address, ' ESTABLISHED')
s, addr = server.accept()  # 4.等待客户端的连接
print(addr, " CONNECTED")
while True:
    content = s.recv(1024)  # 5.接收来自客户端的数据
    if content.decode() == 'EXIT':
        s.close()  # 7.关闭连接
        print(addr, " DISCONNECT")
        break
    print(addr, ':', content.decode())
    # 6.发送数据给客户端
    s.send(bytes(content.decode()+" SUCCESS RECEIVED", encoding='utf-8'))
print("SERVER TERMINATE")
server.close()  # 8.服务端关闭

客户端程序

// TCPClient.py

import socket

hostName = '127.0.0.1'
port = 9000
address = (hostName, port)  # 服务端的地址和端口
# 1.创建socket对象,采用ipv4协议、流式数据传输(面向连接)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(address)  # 2.连接服务器
print("SERVER ConNECT SUCCESS")
print("INPUT 'EXIT' TO TERMINATE")
while True:
    content = input(">>>")
    if(content == 'EXIT'):
        client.send(bytes(content, encoding='utf-8'))
        client.close()
        break
    client.send(bytes(content, encoding='utf-8'))
    content = client.recv(1024)
    print("SERVER RESPONSE:", content.decode())

UDP 客户-服务器程序

服务端程序

// UDPServer.py

import socket

hostName = '127.0.0.1'
port = 9000
address = (hostName, port)
# 1.使用数据报式传输(面向无连接)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(address)  # 2.绑定地址与端口
print("ESTABLISH ", address)
while True:
    content, addr = server.recvfrom(1024)  # 3.接收数据,使用recvfrom
    print(addr, ":", content.decode())
    # 4.使用sendto发送数据
    server.sendto(
        bytes(content.decode()+" SUCCESS RECEIVED", encoding='utf-8'), addr)

客户端程序

// UDPClient.py

import socket

hostName = '127.0.0.1'
port = 9000
address = (hostName, port)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print("INPUT 'EXIT' TO TERMINATE")
while True:
    content = input('>>> ')
    if content == 'EXIT':
        client.close()
        break
    client.sendto(bytes(content, encoding='utf-8'), address)
    content, addr = client.recvfrom(1024)
    print("SERVER RESPONSE:", content.decode('utf-8'))

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5658848.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存