网络编程
用Python进行网络编程,就是在Python程序本身这个进程内,连接别的服务器进程的通信端口进行通信。Python 网络编程和其它语言类似,通常通过”Socket(套接字)”向网络发出请求或者应答网络请求,使主机间或者一台计算机上的进程间可以通讯。
TCPClient
from socket import *
host_name = 'LAPTOP-E02HTJB6' port_num = 1200
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((host_name,port_num))
message = input("enter something: ") clientSocket.send(message.encode())
upperMessage = clientSocket.recv(1024).decode() print('the message from the server: ' + upperMessage)
clientSocket.close()
|
TCPServer
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind((gethostname(), 1200))
serverSocket.listen(2) print('the server is ready to accept information......')
while True: connectionSockte, address = serverSocket.accept()
message = connectionSockte.recv(1024).decode() print('got the message from the client : ' + message)
modifedMessage = message.upper().encode() connectionSockte.send(modifedMessage)
connectionSockte.close()
|