功能说明
客户端向服务器发送一串数据,服务器将这行改成大写并回写给客户端
客户端服务器通讯流程
客户端编程
from socket import *
serverAddress = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverAddress,serverPort))
sentence = raw_input('Input lowercase sentence:')
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
print 'From Server:'+modifiedSentence.decode()
clientSocket.close()
服务端编程
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()
测试结果
启动server
root@virtual-machine:/home/test/python# python TCPServer.py
The server is ready to receive
启动client
root@virtual-machine:/home/test/python# python TCPClient.py
Input lowercase sentence:dfdagfg122
From Server:DFDAGFG122