在Linux中,Python提供了多种库来实现网络通信
服务器端:
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(5)
while True:
client_socket, addr = server_socket.accept()
print("连接地址:", addr)
data = client_socket.recv(1024)
print("接收到的数据:", data.decode())
client_socket.send("Hello from server!".encode())
client_socket.close()
客户端:
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
client_socket.send("Hello from client!".encode())
data = client_socket.recv(1024)
print("接收到的数据:", data.decode())
client_socket.close()
import requests
url = "https://api.example.com/data"
response = requests.get(url)
print("状态码:", response.status_code)
print("响应内容:", response.text)
import urllib.request
url = "https://www.example.com"
response = urllib.request.urlopen(url)
html = response.read().decode()
print("网页内容:", html)
from twisted.internet import protocol, reactor
class MyServer(protocol.Protocol):
def dataReceived(self, data):
print("接收到的数据:", data.decode())
self.transport.write("Hello from server!".encode())
reactor.listenTCP(12345, MyServer())
reactor.run()
这些库都可以帮助你在Linux中使用Python实现网络通信。你可以根据自己的需求选择合适的库进行编程。