Python教程

Python3 网络编程(使用Socket实现TCP、UDP通信)

本文主要是介绍Python3 网络编程(使用Socket实现TCP、UDP通信),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

TCP通信

TCP_服务端

 1 import socket as s
 2 
 3 tcp = s.socket(s.AF_INET,s.SOCK_STREAM)
 4 tcp.bind(('127.0.0.1', 6666))
 5 tcp.listen(5)
 6 while True:
 7     # 建立客户端连接
 8     clientsocket,addr = tcp.accept()      
 9     print("连接地址: %s" % str(addr))
10     msg = '欢迎访问{}!'.format(tcp.getsockname())+ "\r\n"
11     clientsocket.send(msg.encode('utf-8'))
12     clientsocket.close()

TCP_客户端

import socket as s

tcp = s.socket(s.AF_INET,s.SOCK_STREAM)
tcp.connect(('127.0.0.1', 6666))
msg = tcp.recv(1024)
tcp.close()
print (msg.decode('utf-8'))

UDP通信

UDP_服务端

import socket

BUFSIZE = 1024
ip_port = ('127.0.0.1', 9999)
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # udp协议
server.bind(ip_port)
while True:
    data,client_addr = server.recvfrom(BUFSIZE)
    print('client地址:', client_addr,'server收到的数据:', data.decode("UTF-8"))
    server.sendto(data,client_addr)
server.close()

UDP_客户端

import socket
BUFSIZE = 1024

client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
    msg = input(">>").strip()
    ip_port = ('127.0.0.1', 9999)
    client.sendto(msg.encode('utf-8'),ip_port)
 
    data,server_addr = client.recvfrom(BUFSIZE)
    print(server_addr,'服务端收到: ',data.decode("UTF-8"))

client.close()

 

这篇关于Python3 网络编程(使用Socket实现TCP、UDP通信)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!