您好,登錄后才能下訂單哦!
本文實例講述了Python基于socket實現簡單的即時通訊功能。分享給大家供大家參考,具體如下:
客戶端tcpclient.py
# -*- coding: utf-8 -*- import socket import threading # 目標地址IP/URL及端口 target_host = "127.0.0.1" target_port = 9999 # 創建一個socket對象 client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 連接主機 client.connect((target_host,target_port)) def handle_send(): while True: content = raw_input() client.send(content) def handle_receive(): while True: response = client.recv(4096) print response send_handler = threading.Thread(target=handle_send,args=()) send_handler.start() receive_handler = threading.Thread(target=handle_receive,args=()) receive_handler.start()
服務器端tcpserver.py
# -*- coding: utf-8 -*- import socket import threading # 監聽的IP及端口 bind_ip = "127.0.0.1" bind_port = 9999 #socket 服務器初始化 server = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server.bind((bind_ip,bind_port)) server.listen(5) print "[*] Listening on %s:%d" % (bind_ip,bind_port) # 定義函數handle_client,輸入參數client_socket def handle_client(): while True: request = client_socket.recv(1024) print "[*] Received:%s" % request def handle_send(): while True: content = raw_input() client_socket.send(content); #阻塞在這里,等待接收客戶端的數據 client_socket,addr = server.accept() print "[*] Accept connection from:%s:%d" % (addr[0],addr[1]) #創建一個線程 client_handler = threading.Thread(target=handle_client,args=()) client_handler.start() send_handler = threading.Thread(target=handle_send,args=()) send_handler.start()
更多關于Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。