欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)的多任務(wù)版udp聊天器功能案例

 更新時(shí)間:2019年11月13日 11:39:39   作者:小飛俠v科比  
這篇文章主要介紹了python實(shí)現(xiàn)的多任務(wù)版udp聊天器功能,結(jié)合具體案例形式分析了Python基于udp的聊天器功能相關(guān)實(shí)現(xiàn)與使用技巧,需要的朋友可以參考下

本文實(shí)例講述了python實(shí)現(xiàn)的多任務(wù)版udp聊天器。分享給大家供大家參考,具體如下:

說(shuō)明

編寫一個(gè)有2個(gè)線程的程序
線程1用來(lái)接收數(shù)據(jù)然后顯示
線程2用來(lái)檢測(cè)鍵盤數(shù)據(jù)然后通過(guò)udp發(fā)送數(shù)據(jù)

要求

實(shí)現(xiàn)上述要求
總結(jié)多任務(wù)程序的特點(diǎn)

參考代碼:

import socket
import threading
def send_msg(udp_socket):
  """獲取鍵盤數(shù)據(jù),并將其發(fā)送給對(duì)方"""
  while True:
    # 1. 從鍵盤輸入數(shù)據(jù)
    msg = input("\n請(qǐng)輸入要發(fā)送的數(shù)據(jù):")
    # 2. 輸入對(duì)方的ip地址
    dest_ip = input("\n請(qǐng)輸入對(duì)方的ip地址:")
    # 3. 輸入對(duì)方的port
    dest_port = int(input("\n請(qǐng)輸入對(duì)方的port:"))
    # 4. 發(fā)送數(shù)據(jù)
    udp_socket.sendto(msg.encode("utf-8"), (dest_ip, dest_port))
def recv_msg(udp_socket):
  """接收數(shù)據(jù)并顯示"""
  while True:
    # 1. 接收數(shù)據(jù)
    recv_msg = udp_socket.recvfrom(1024)
    # 2. 解碼
    recv_ip = recv_msg[1]
    recv_msg = recv_msg[0].decode("utf-8")
    # 3. 顯示接收到的數(shù)據(jù)
    print(">>>%s:%s" % (str(recv_ip), recv_msg))
def main():
  # 1. 創(chuàng)建套接字
  udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  # 2. 綁定本地信息
  udp_socket.bind(("", 7890))
  # 3. 創(chuàng)建一個(gè)子線程用來(lái)接收數(shù)據(jù)
  t = threading.Thread(target=recv_msg, args=(udp_socket,))
  t.start()
  # 4. 讓主線程用來(lái)檢測(cè)鍵盤數(shù)據(jù)并且發(fā)送
  send_msg(udp_socket)
if __name__ == "__main__":
  main()

更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論