一、套接字
套接字(socket)是同一台主机内应用层和运输层的接口。 进程可类比为一个房子,套接字为该进程的门,当一个进程想向另一台主机发送报文时,该进程把报文推出门(套接字),通过运输层的运输到另一台主机的目的进程,一旦报文到达目的主机,它通过接收进程的门(套接字)传递,接收进程开始处理报文。 可以看到,应用程序开发者在套接字应用层一侧可以控制所有,但是几乎无法控制运输层。
二、UDP编程
1、UDPServer
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_DGRAM)
serverSocket.bind(('',serverPort))
print("The server is ready to receive")
while True:
message,clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.decode().upper()
serverSocket.sendto(modifiedMessage.encode(), clientAddress)
2、UDPClient
from socket import *
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET,SOCK_DGRAM)
message = input('Input lowercase sentence:')
clientSocket.sendto(message.encode(),(serverName,serverPort))
modifiedMessage,serverAddresss = clientSocket.recvfrom(2048)
print(modifiedMessage.decode())
clientSocket.close()
三、TCP编程
1、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:
connectSocket,addr = serverSocket.accept()
Message = connectSocket.recv(1024).decode()
capitalizedMessage = Message.upper()
connectSocket.send(capitalizedMessage.encode())
connectSocket.close()
2、TCPClient
from socket import *
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
message = input('Input Message:')
clientSocket.send(message.encode())
modifiedMessage = clientSocket.recv(1024)
print('From Server:',modifiedMessage.decode())
clientSocket.close()
|