TCP socket编程


server

from socket import *
serverName = 'localhost'
serverPort = 2333
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((serverName, serverPort))
serverSocket.listen(1)
while True:
    connectionSocket, addr = serverSocket.accept() # 新建TCP连接,完成三次握手
    message = connectionSocket.recv(2048)
    connectionSocket.send( message.decode().upper().encode() )
    connectionSocket.close()


client

from socket import *
serverName = 'localhost'
serverPort = 2333
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
message = raw_input('input lowercase sentences:') #py2.x
clientSocket.send(message.encode())
modifiedMessage = clientSocket.recv(2048)
clientSocket.close()
print modifiedMessage

你可能感兴趣的:(TCP socket编程)