网络编程
TCP编程
客户端
'''
客户端:创建TCP连接时,主动发起连接的叫做客户端
服务端:接收客户端的连接
'''
import socket
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.connect(("www.sina.com.cn", 80))
sk.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
data = []
while True:
tempData = sk.recv(1024)
if tempData:
data.append(tempData)
else:
break
dataStr = (b''.join(data)).decode("utf-8")
sk.close()
headers, HTML = dataStr.split('\r\n\r\n', 1)
print(headers)
print(HTML)
客户端与服务器间的数据交互
client.py
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("192.168.0.102", 8080))
while True:
data = input("请输入给服务器发送的数据")
client.send(data.encode("utf-8"))
info = client.recv(1024)
print("服务器说:", info.decode("utf-8"))
service.py
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('192.168.0.102',8080))
server.listen(5)
print("服务器启动成功。。。。。。。。。。。。。")
clientSocket, clientAddress = server.accept()
print("%s----%s连接成功"%(str(clientAddress),clientAddress))
while True:
data = clientSocket.recv(1024)
print("客户端说:" + data.decode("utf-8"))
sendData = input("输入返回给客户端的数据")
clientSocket.send(sendData.encode('utf-8'))
'''
while True:
#等待客户端连接
clientSocket, clientAddress = server.accept()
#启动一个线程,将当前连接的clientSocket交给线程
'''
UDP编程
客户端与服务端通信
client.py
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
data = input("请输入数据")
client.sendto(data.encode("utf-8"), ("192.168.0.102", 8900))
info = client.recv(1024).decode('utf-8')
print("服务器说:", info)
service.py
import socket
udpServer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpServer.bind(("192.168.0.102", 8900))
while True:
data, addr = udpServer.recvfrom(1024)
print("客户端说:", data.decode("utf-8"))
info = input("请输入数据")
udpServer.sendto(info.encode("utf-8"), addr)
|