您好,登錄后才能下訂單哦!
Python 超簡(jiǎn)單的聊天程序
客戶端:
import socket, sys host = '10.248.27.23' # host = raw_input("Plz imput destination IP:") # data = raw_input("Plz imput what you want to submit:") port = 51423 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((host, port)) except socket.gaierror, e: print "Address-related error connecting to server: %s" %e sys.exit(1) except socket.error, e: print "Connection error: %s" %e sys.exit(1) while 1: try: data = raw_input("I say: ") s.send(data) buf = s.recv(1024) if len(buf): print "he say: "+buf except: print "Dialogue Over" s.close() sys.exit(0)
import socket, traceback, sys host = '' port = 51423 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((host, port)) s.listen(1) ClientSock, ClientAddr = s.accept() while 1: try: buf = ClientSock.recv(1024) if len(buf): print "he say: "+buf data = raw_input("I say: ") ClientSock.sendall(data) except: print "Dialogue Over" ClientSock.close() sys.exit(0)
模擬qq聊天,語(yǔ)言環(huán)境:Python3
示例代碼:
# 編寫(xiě)一個(gè)程序,模擬qq聊天 # 要求:程序可以同時(shí)發(fā)消息和收消息,發(fā)和收的過(guò)程中程序不退出 # 思路:使用socket來(lái)完成(socket 是全雙工模式,可以實(shí)現(xiàn)收和發(fā)同時(shí)進(jìn)行),定義倆個(gè)線程,一個(gè)負(fù)責(zé)發(fā)消息、一個(gè)負(fù)責(zé)收消息 from threading import Thread from socket import * def rec_data(): while True: rec_info = udpsocket.recvfrom(1024) print("\r>>%s:%s" % (rec_info[1], rec_info[0].decode("gb2312"))) print("<<", end="") def send_date(): while True: send_mes = input("<<") udpsocket.sendto(send_mes.encode("gb2312"), (desip, desport)) udpsocket = None desip = "" desport = 0 def main(): global udpsocket global desip global desport desip = input("對(duì)方IP:") desport = int(input("對(duì)方端口:")) udpsocket = socket(AF_INET, SOCK_DGRAM) udpsocket.bind(("", 9001)) tr = Thread(target=rec_data) ts = Thread(target=send_date) tr.start() ts.start() tr.join() ts.join() if __name__ == '__main__': main()
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)億速云的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。