https://home.cnblogs.com/group/topic/8550.html

计算机网络-实验一-socket编程TCP UDP

UDPServer

# coding=utf-8
from socket import *

serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)  # 创建UDP socket
serverSocket.bind(('', serverPort))  # 绑定socket 到本地端口 12000
print("The server is ready to receive")
while True:
    message, clientAddress = serverSocket.recvfrom(2048)  # UDP socket 读取 message, 获得(client IP and port)
    modifiedMessage = message.decode().upper()  # 打包大写的字符串
    serverSocket.sendto(modifiedMessage.encode(), clientAddress)

UDPClient

# coding=utf-8
from socket import *

serverName = '127.0.0.1'  # 可以是IP,也可以是主机名,若是主机名,会自动调用DNS解析
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_DGRAM)  # 创建UDP socket#AF_INET表示IPv4协议,datagram表示数据块传输,即UDP
message = input('Input lowercase sentence:')
address=(serverName,serverPort)
clientSocket.sendto(message.encode(),address)  # 编码并打包IP端口; 放到socket里
# 端口进行打包,(自动把本地ip端口也打包了)
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)  # 读取返回的消息
# 后面是缓存大小,只读取前2k字节的内容
print(modifiedMessage.decode())  # 在屏幕上打印
clientSocket.close()  # 关闭 socket

在这里插入图片描述在这里插入图片描述
TCPServer

from socket import *

serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print("The server is ready to receive")
while True:
    connectionSocket, addr = serverSocket.accept()
    sentence = connectionSocket.recv(1024).decode()
    capitalizedSentence = sentence.upper()
    connectionSocket.send(capitalizedSentence.encode())
    connectionSocket.close()

TCPClient

from socket import *
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = input('Input lowercase sentence:')
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
print ('From Server:', modifiedSentence.decode())
clientSocket.close()

在这里插入图片描述在这里插入图片描述

posted @ 2020-05-07 22:22  xcsxchen  阅读(821)  评论(0编辑  收藏  举报