python socket编程5 - 最简单的命令行启动的tcp/udp server/client例子

一、TCP 服务端和客户端

1、server 服务端

from socket import *

serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print('TCP server 已经启动...')

while True:
    print('服务器已经准备接受客户端...')
    # 阻塞,等待客户端的连接
    clientSocket, addr = serverSocket.accept()
    print('已经有客户端连接')

    # 接受客户端发送的信息
    sentence = clientSocket.recv(1024).decode()

    # 将接受内容(小写字母组成的句子)全部转成大写字母
    capitalizedSentence = sentence.upper()

    # 发送大写字母组成的句子
    clientSocket.send(capitalizedSentence.encode())

    # 关闭客户端连接
    clientSocket.close()

2、client 客户端

from socket import *

serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)

# 连接服务器
clientSocket.connect((serverName, serverPort))
# 接受输入
sentence = input('输入小写字母组成的句子:')

# 发送小写字母组成的句子
clientSocket.send(sentence.encode())

# 接受服务器返回的大写字母组成的句子
modifiedSentence = clientSocket.recv(1024)
print('服务端返回:', modifiedSentence.decode())

# 关闭客户端连接
clientSocket.close()

二、UDP 服务端和客户端

1、server 服务端

from socket import *

serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print('UDP服务已经启动...')
while True:
    message, clientAddress = serverSocket.recvfrom(2048)
    modifiedMessage = message.decode().upper()
    serverSocket.sendto(modifiedMessage.encode(), clientAddress)

2、client 客户端

from socket import *

serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = input('输入小写字母组成的句子:')
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print(“服务端返回的内容为:”+modifiedMessage.decode())
clientSocket.close()

后面的例子会参照上面的例子进行扩展。

你可能感兴趣的:(python,socket编程,python,python,tcp/ip,udp,socket)