[英]Create messaging system in python using socket programming
我是socket編程的新手。 我想在服務器和客戶端之間創建一個簡單的消息傳遞系統(聊天)。 我在下面提供了我的代碼。 我希望它能像聊天系統一樣工作,但它不起作用。 如果消息被發送,它應該接收並打印出來但僅在給出輸入后打印接收的字符串。 我期待它應該並行運行(接收消息並發送消息)。
服務器:
import socket
import time
import threading
def get(s):
tm = s.recv(1024)
print("\nReceived: ",tm.decode('ascii'))
def set_(s):
i=input("\nEnter : ")
s.send(i.encode('ascii'))
serversocket = socket.socket()
host = socket.gethostname()
port = 9981
serversocket.bind((host,port))
serversocket.listen(1)
clientsocket,addr = serversocket.accept()
while(1):
t1=threading.Thread( target = get , args = (clientsocket,) )
t1.start()
t2=threading.Thread( target = set_ , args = (clientsocket,) )
t2.start()
time.sleep(10)
clientsocket.close()
客戶:
import socket
import threading
import time
def get(s):
tm = s.recv(1024)
print("\nReceived: ",tm.decode('ascii'))
def set_(s):
i=input("\nEnter : ")
s.send(i.encode('ascii'))
s = socket.socket()
host = socket.gethostname()
port = 9981
s.connect((host,port))
while(1):
t1=threading.Thread( target = get , args = (s,) )
t2=threading.Thread( target = set_ , args = (s,) )
t1.start()
t2.start()
time.sleep(10)
s.close()
輸出(在客戶端):
Enter: hello ------------------------------>(1)
Received: hello --------------------------->(3)
輸出(在服務器上):
Enter: hello ------------------------------>(2)
Received : hello ------------------------->(4)
預期產出:
輸出(在客戶端):
Enter: hello ------------------------------>(1)
Received: hello --------------------------->(4)
輸出(在服務器上):
Received : hello ------------------------->(2)
Enter: hello ------------------------------>(3)
數字代表執行順序。
程序的線程邏輯存在問題。 您應該將while(True)
循環移動到線程工作者,並且只啟動一次線程。 就目前而言,您的代碼每10秒只能發送/接收一條消息。
服務器:
import socket
import threading
def get(s):
while True:
tm = s.recv(1024)
print("\nReceived: ",tm.decode('ascii'))
def set_(s):
while True:
i=input("\nEnter : ")
s.send(i.encode('ascii'))
serversocket = socket.socket()
host = socket.gethostname()
port = 9981
serversocket.bind((host,port))
serversocket.listen(1)
clientsocket,addr = serversocket.accept()
t1=threading.Thread( target = get , args = (clientsocket,) )
t1.start()
t2=threading.Thread( target = set_ , args = (clientsocket,) )
t2.start()
客戶:
import socket
import threading
def get(s):
while True:
tm = s.recv(1024)
print("\nReceived: ",tm.decode('ascii'))
def set_(s):
while True:
i=input("\nEnter : ")
s.send(i.encode('ascii'))
s = socket.socket()
host = socket.gethostname()
port = 9981
s.connect((host,port))
t1=threading.Thread( target = get , args = (s,) )
t2=threading.Thread( target = set_ , args = (s,) )
t1.start()
t2.start()
您需要以不同的方式處理關閉套接字,並且由於程序的多線程特性,輸入/接收的打印在第一條消息之后變得不同步,但輸入仍在等待。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.