python练习题-03
- 使用TCP协议完成两台主机之间的消息通信。
import socket
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip_port = ('192.168.0.102', 12335)
tcp_client.connect(ip_port)
while True:
data = input("请输入信息:")
if data == "quit":
break
else:
tcp_client.send(data.encode('utf-8'))
recvdata = tcp_client.recv(1024)
print('回复:', recvdata.decode('utf-8'))
tcp_client.close()
import socket
tcp_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip_port = ('', 12333)
tcp_server.bind(ip_port)
tcp_server.listen(5)
print("监听中...")
client_socket, client_ip_port = tcp_server.accept()
while True:
recv_data = client_socket.recv(1024)
print("接收:", recv_data.decode())
if not recv_data:
break
else:
send_data = input("回复:")
client_socket.send(send_data.encode('utf-8'))
tcp_server.close()
- 使用UDP协议完成两台主机之间的消息通信
import socket
udp_server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
local_addr = ('', 12300)
udp_server.bind(local_addr)
print('监听中...')
while 1:
recvdata, addr = udp_server.recvfrom(1024)
print("客户端:", recvdata.decode())
#输入quit退出
if recvdata == "quit":
break
message = input("请输入内容:")
udp_server.sendto(message.encode('utf-8'), addr)
udp_server.close()
import socket
udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip_port = ("192.168.0.101", 12300)
while 1:
data =input("请输入信息:")
#输入quit退出
if data == "quit":
break
udp_client.sendto(data.encode('utf-8'), ip_port)
message = udp_client.recv(1024)
print("服务器:", message.decode())
udp_client.close()