计算机网络-基于python的TCP套接字编程

运行环境: Pycharm 2021.3.1/python 3.9

 TCPClient.py

from socket import *

# TCP客户端 2022/02/26

# 定义服务端IP及端口号
serverIP = '127.0.0.1'
serverPort = 997
# 创建客户套接字
clientSocket = socket(AF_INET, SOCK_STREAM)
# 与服务器端欢迎套接字进行三次握手创建TCP连接
clientSocket.connect((serverIP, serverPort))
# 输入message
message = input('Please input your message : ')
# 与服务器连接套接字通信发送message
clientSocket.send(message.encode())
# 接收
modifiedMessage = clientSocket.recv(1024)
# 在控制台输出
print(modifiedMessage.decode())
# 关闭
clientSocket.close()

TCPServer.py

from socket import *

# TCP服务器端 2022/02/26

# 定义服务器欢迎套接字端口号
serverPort = 997
# 创建欢迎套接字
serverSocket = socket(AF_INET, SOCK_STREAM)
# 绑定端口号和欢迎套接字
serverSocket.bind(('', serverPort))
print('The server is ready to listen !')
# 欢迎套接字等待并聆听客户敲门
serverSocket.listen(1)
# 监听到至少1位客户时进入循环
while 1:
    # 创建连接套接字
    connectionSocket, clientAddress = serverSocket.accept()
    print('The server is ready to accept !')
    # 接收message
    message = connectionSocket.recv(1024)
    print('-------Received message: ' + message.decode() + '-------')
    # 处理
    modifiedMessage = message.upper()
    print(modifiedMessage.decode())
    # 发送
    connectionSocket.send(modifiedMessage)
    print('------- I MADE IT ! -------')
    # 关闭连接套接字
    connectionSocket.close()

运行结果:

计算机网络-基于python的TCP套接字编程_第1张图片

计算机网络-基于python的TCP套接字编程_第2张图片 

你可能感兴趣的:(python,网络,socket)