新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
python使用udp實(shí)現(xiàn)聊天器功能-創(chuàng)新互聯(lián)
聊天器簡易版
使用udp實(shí)現(xiàn)一個(gè)簡單的聊天器程序,要求如下:
•在一個(gè)電腦中編寫1個(gè)程序,有2個(gè)功能
•1.獲取鍵盤數(shù)據(jù),并將其發(fā)送給對方
•2.接收數(shù)據(jù)并顯示
•并且功能數(shù)據(jù)進(jìn)行選擇以上的2個(gè)功能調(diào)用
例子程序如下:
import socket def send_message(udp_socket): # 輸入對方的ip/port dest_ip = input("請輸入對方的ip:") dest_port = int(input("請輸入對象的port:")) # 讀取輸入的數(shù)據(jù) send_data = input('請輸入要發(fā)送的數(shù)據(jù):') # 發(fā)送數(shù)據(jù) dest_addr = (dest_ip, dest_port) udp_socket.sendto(send_data.encode('GBK'), dest_addr) def recv_message(udp_socket): # 接收數(shù)據(jù) recv_data = udp_socket.recvfrom(1000) print("%s:%s" % (recv_data[1], recv_data[0].decode("utf-8"))) def main(): # 創(chuàng)建套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: send_message(udp_socket) recv_message(udp_socket) # 關(guān)閉 udp_socket.close() if __name__ == '__main__': main()
網(wǎng)頁題目:python使用udp實(shí)現(xiàn)聊天器功能-創(chuàng)新互聯(lián)
分享網(wǎng)址:http://fisionsoft.com.cn/article/hhpgi.html