您好,登錄后才能下訂單哦!
用Python實現點對點的聊天,2個程序,一個是client.py,一個是server.py,通過本機地址127.0.0.1連接進行通信,利用多線程把發送消息和接收消息分開獨立進行。
client代碼:
import socket import sys import threading import time class client(): def __init__(self): self.s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.ip = "127.0.0.1" def connect(self): try: self.s.connect((self.ip,8888)) print("connect success") print('connect time: '+time.ctime()) except ConnectionError: print('connect error') sys.exit(-1) except: print('unexpect error') sys.exit(-1) def send_sth(self): while True: sth=input('say something:\n') try: self.s.sendall(sth.encode('utf-8')) except ConnectionError: print('connect error') sys.exit(-1) except: print('unexpect error') sys.exit(-1) def receive(self): while True: try: r=self.s.recv(1024) print ('get message:'+r.decode('utf-8')) except ConnectionError: print('connect error') sys.exit(-1) except: print('unexpect error') sys.exit(-1) c1 = client() c1.connect() threading._start_new_thread(c1.receive,()) c1.send_sth()
server代碼:
import socket import sys import threading import time def server(): def bind(): HOST='127.0.0.1' s.bind((HOST,8888)) print("bind ok") def listen(): s.listen(10) print ('Socket now listening') def send_sth(conn): while True: try: sth=input('say something:\n') conn.sendall(sth.encode('utf-8')) except ConnectionError: print('connect error') sys.exit(-1) except: print('unexpect error') sys.exit(-1) def recv(conn): while True: try: data=conn.recv(1024) data2=data.decode('utf-8') print('get message:'+data2) except ConnectionError: print('connect error') sys.exit(-1) except: print('unexpect error') sys.exit(-1) s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) bind() listen() conn,addr=s.accept() print("connect success") print('connect time: '+time.ctime()) threading._start_new_thread(recv,(conn,)) send_sth(conn) if __name__=='__main__': server()
開啟多線程有2種方法,上面2個程序都是用函數的方法,還有一種方法是用類繼承threading類
代碼:
import socket import threading class client(threading.Thread): def __init__(self,sth): threading.Thread.__init__(self) self.sth=sth def run(self): s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) ip="127.0.0.1" try: s.connect((ip,8888)) except : print('con error') exit() #print("connect success") s.sendall(self.sth.encode('utf-8')) #print("send success") try: r=s.recv(1024) except: print('recv error') exit() print (r.decode('utf-8')) c1=client('hello 1') c1.start() c2=client('hello 2') c2.start()
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。