python使用多執行緒實現UDP聊天器

2021-10-06 17:41:06 字數 1174 閱讀 8460

import socket

import threading

defsend_msg

(udp_socket, dest_ip, dest_port)

:"""傳送資料"""

while

true

: send_data =

input

("請輸入要傳送的資料:"

) udp_socket.sendto(send_data.encode(

"utf-8"),

(dest_ip, dest_port)

)def

recv_msg

(udp_socket)

:"""接收資料並顯示"""

while

true

: recv_data = udp_socket.recvfrom(

1024

)print

(recv_data)

defmain()

:"""完成udp聊天器的整體控制"""

# 1.建立套接字

udp_socket = socket.socket(socket.af_inet, socket.sock_dgram)

# 2.繫結本地資訊

udp_socket.bind((""

,7890))

# 3.獲取對方ip

dest_ip =

input

("請輸入對方ip"

) dest_port =

int(

input

("請輸入對方的port:"))

# 4.建立兩個執行緒,去執行相應的功能

t_recv = threading.thread(target = recv_msg, args=

(udp_socket,))

t_send = threading.thread(target = send_msg, args=

(udp_socket, dest_ip, dest_port)

) t_recv.start(

) t_send.start(

)if __name__ ==

"__main__"

: main(

)

python多執行緒實現

資料夾命名不能用官方已有的模組名比如threading.py test.py等等都會報錯 from multiprocessing import process import os 子程序要執行的 def run proc name print run child process s s name,...

python多執行緒實現

coding utf 8 import threading 匯入執行緒模組 from time import ctime,sleep 建立執行緒事件 defeat print 我在吃東西 s ctime 執行緒組 threads 建立執行緒數量 for x in range 10 t1 thread...

python使用socket實現多執行緒埠掃瞄

使用socket主要是判斷是否埠能否聯通 socket 詳情參考 1.socket.connect 檢測埠,若埠不能聯通,則會丟擲異常,若無異常,則埠存活,使用try except異常捕獲處理,進而進行埠掃瞄 這裡將使用100個執行緒,每個埠連線都要檢查是否超過65535 coding utf8 i...