您好,登錄后才能下訂單哦!
Python 超簡單的聊天程序
客戶端:
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聊天,語言環境:Python3
示例代碼:
# 編寫一個程序,模擬qq聊天 # 要求:程序可以同時發消息和收消息,發和收的過程中程序不退出 # 思路:使用socket來完成(socket 是全雙工模式,可以實現收和發同時進行),定義倆個線程,一個負責發消息、一個負責收消息 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("對方IP:") desport = int(input("對方端口:")) 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()
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對億速云的支持。如果你想了解更多相關內容請查看下面相關鏈接
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。