Python UDP和TCP套接字简单创建和连接

目的:客户端输入小写字母转成大写

UDP

#服务器端
from socket import *
serverPort=12000
serverName='127.0.0.1'
serverSocket=socket(AF_INET,SOCK_DGRAM)
serverSocket.bind((serverName,serverPort))
print("the server is ready to work")
while True:
	message,clientaddress=serverSocket.recvfrom(2048)
	modifiedMessage=message.decode().upper()
	serverSocket.sendto(modifiedMessage.encode(),clientaddress)
#客户端
from socket import *
serverName='127.0.0.1'
serverPort=12000
clientSocket=socket(AF_INET,SOCK_DGRAM)
message=input('please Input lower\n')
clientSocket.connect((serverName, serverPort))
clientSocket.sendto(message.encode(),(serverName,serverPort))
modifiedMessage,serverAddress=clientSocket.recvfrom(2048)
print(modifiedMessage.decode())
clientSocket.close()

TCP

#服务器端
from socket import *
ip = '127.0.0.1'
port = 12000
severSocket = socket(AF_INET,SOCK_STREAM)
severSocket.bind((ip,port))
severSocket.listen(5)
print('the server is ready')
while True:
    connectSocket,addr = severSocket.accept()
    recvsen = connectSocket.recv(1024).decode()
    mosen = recvsen.upper()
    connectSocket.send(mosen.encode())
    connectSocket.close()
#客户端
from socket import *
ip = '127.0.0.1'
port = 12000
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((ip,port))
sen = input('please lower letter\n')
clientSocket.send(sen.encode())
recvmessage = clientSocket.recv(1024).decode()
print(recvmessage)
clientSocket.close()
上一篇:C#实现长连接


下一篇:LNMP简要配置