python socket 之 udp
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
def socket_send(socket_send):
ip_add = input("server ip is: ").strip()
ip_port = int(input("sever port is: ").strip())
send_data = input("please send data: ")
socket_send.sendto(send_data.encode("utf-8"), (ip_add, ip_port))
def socket_receive(socket_receive):
recv_data = socket_receive.recvfrom(1024)
recv_mesg = recv_data[0]
recv_addr = recv_data[1]
print("%s" % str(recv_addr))
print("%s" % recv_mesg.decode("utf-8"))
def main():
try:
socket_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
local_addr_port = ("", 8081)
socket_udp.bind(local_addr_port)
while True:
print("---------聊天器----------")
socket_receive(socket_udp)
socket_send(socket_udp)
except Exception as result:
print("unknown error: %s" % result)
finally:
socket_udp.close()
if __name__ == "__main__":
main()
client端
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
def socket_send(socket_send):
ip_add = input("server ip is: ").strip()
ip_port = int(input("sever port is: ").strip())
send_data = input("please send data: ")
socket_send.sendto(send_data.encode(“utf-8”), (ip_add, ip_port))
def socket_receive(socket_receive):
recv_data = socket_receive.recvfrom(1024)
recv_mesg = recv_data[0]
recv_addr = recv_data[1]
print("%s" % str(recv_addr))
print("%s" % recv_mesg.decode("utf-8"))
def main():
try:
socket_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
local_addr_port = ("", 8080)
socket_udp.bind(local_addr_port)
while True:
print("---------聊天器----------")
socket_send(socket_udp)
socket_receive(socket_udp)
except Exception as result:
print("unknown error: %s" % result)
finally:
socket_udp.close()
if __name__ == "__main__":
main()