Python使用Socket實(shí)現(xiàn)簡單聊天程序
b2b模式的聊天工具
服務(wù)端:
# 鏈接while True: print(’等待連接...’) sock,adr = server_socket.accept() while True: try: # 接受數(shù)據(jù) data = sock.recv(1024) print(adr[0] + ’發(fā)來消息:’, data.decode()) # 發(fā)送數(shù)據(jù) send_msg = input('請(qǐng)輸入發(fā)送內(nèi)容>>').strip() sock.send(send_msg.encode(’utf-8’)) except ConnectionResetError as e: print(’%s斷開連接!’ %adr[0]) break # 關(guān)閉本次連接 sock.close()# 關(guān)閉socketserver_socket.close()
客戶端:
import socket# 設(shè)置服務(wù)器ip和端口號(hào)host_ip = ’192.168.31.207’port = 8896client_socket = socket.socket()client_socket.connect((host_ip,port))while True: send_msg = input(’請(qǐng)輸入內(nèi)容>>’).strip() if send_msg == ’’: continue client_socket.send(send_msg.encode()) recv_data = client_socket.recv(1024) print(host_ip+'回復(fù):'+recv_data.decode())client_socket.close()
目前只支持客戶端發(fā)一句,服務(wù)端發(fā)一句這種模式。
超過一句內(nèi)容后,發(fā)出去的內(nèi)容對(duì)方接收不到
結(jié)果:
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. .Net Core和RabbitMQ限制循環(huán)消費(fèi)的方法2. jsp文件下載功能實(shí)現(xiàn)代碼3. ASP動(dòng)態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享4. JSP之表單提交get和post的區(qū)別詳解及實(shí)例5. Xml簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理6. vue3+ts+elementPLus實(shí)現(xiàn)v-preview指令7. phpstudy apache開啟ssi使用詳解8. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器9. 詳解瀏覽器的緩存機(jī)制10. 如何在jsp界面中插入圖片
