python使用socket實現雙工通訊

2021-09-25 20:35:40 字數 1275 閱讀 5387

import socket

def send_msg(udp_socket):

「」「傳送訊息」""

# 獲取需要傳送的類容

send_data = input(「請輸入需要傳送的類容:」)

# 獲取ip端

dest_ip = input(「請輸入對方的ip:」)

dest_port = int(input(「請輸入對方的埠:」))

# 傳送資料

udp_socket.sendto(send_data.encode(「gbk」), (dest_ip, dest_port))

def recv_msg(udp_socket):

「」「接收訊息」""

# 接收資料最大長度1024

recv_data = udp_socket.recvfrom(1024)

# 解析出收到的資料

# recv_data這個變數接收的是乙個元組(接收到的資料(傳送方ip, port))

recv_msg = recv_data[0] # 儲存接收到的資料

send_addr = recv_data[1] # 儲存傳送方ip和埠

# 3.列印接收到的資料

def main():

# 建立套接字

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

# 繫結資訊 這裡繫結的資料是乙個元組

udp_socket.bind(("", 1234))

# 迴圈處理收發資料

while true:

print("-----***聊天器-----")

print("1:傳送訊息")

print("2:接收訊息")

print("0:退出系統")

op = input("請輸入需要執行的操作:")

if op == "1":

# 傳送資料

send_msg(udp_socket)

elif op == "2":

# 接收資料

recv_msg(udp_socket)

elif op == "0":

print("退出系統聊天")

break

else:

print("輸入不正確請重新選擇")

ifname== 「main」:

main()

python實現socket收發資料的實現

1.建立套接字 2.使用套接字收 發資料 3.關閉套接字 import socket def main 建立套接字 udp socket socket.socket socket.af inet,socket.sock dgram 繫結資訊 這裡繫結的資料是乙個元組 udp socket.bind ...

socket 使用select 非阻塞方式實現

select函式原型如下 int select int maxfds,fd set readfds,fd set writefds,fd set exceptfds,struct timeval timeout select系統呼叫是用來讓我們的程式監視多個檔案控制代碼 socket 控制代碼 的狀...

python中Socket的使用

前一段時間學習python網路程式設計,完成簡單的通過python實現網路通訊的功能。現在,將python中socket 通訊的基本實現過程做乙個記錄備份.python 中的socket通訊較為簡單,僅需要幾行 就可實現。和一般的網路通訊一樣,通訊方式分為udp和tcp兩種方式,兩種方式的處理也略有...