一句廢話:最近學習python核心編程,遇到了運行簡單的(有多簡單自己看)tcp服務器與客戶端黑屏閃退的問題
原因:
>>>from socket import *
>>> help(socket.recv)
Help on method_descriptor:
recv(...)
recv(buffersize[, flags]) -> data
Receive up to buffersize bytes from the socket.
>>> help(socket.send)
Help on method_descriptor:
send(...)
send(data[, flags]) -> count
Send a data string to the socket.
因爲工作模式爲:客戶端發送-服務器接收-服務器發送-客戶端接收
即客戶端發送的數據類型必須符合服務器接收的數據類型,即字節流,表現爲
客戶端:發送,data.encode(),因爲要給服務器接收用
服務器:接收,data.decode(),因爲要給服務器send用
服務器:發送,data.encode(),因爲要給客戶端接收用
客戶端:接收,data.decode,因爲要顯示輸出
詳細代碼如下:
服務器:
from socket import *
from time import ctime
Host=''
Port=3306
BufSIZE=1024
Addr=(Host,Port)
Sst=socket(AF_INET,SOCK_STREAM)
Sst.bind(Addr)
Sst.listen(5)
while True:
print('....Wait Connect....')
Cst,Addr=Sst.accept()
print('....Connect From ',Addr,'....')
while True:
data=Cst.recv(BufSIZE).decode()
Cst.send(data.encode())
Cst.close()
Sst.close()
客戶端:
from socket import *
Host='localhost'
Port=3306
BuffSIZE=1024
Addr=(Host,Port)
Cst=socket()
Cst.connect(Addr)
while True:
data=input('>').encode()
Cst.send(data)
data=Cst.recv(BuffSIZE).decode()
print('>:',data)
不足之處,敬請諒解,同時請幫忙指正,不勝感激。
附有如下問題:
1.socket.send()要求是字符串的參數,data.encode()爲什麼不報錯,編碼之後指定不是字符串了呀?
2.tcp服務器是個死循環,但是當關閉客戶端的時候,它報個異常就退出了,怎麼改變?
3.客戶端也是個死循環,當服務器關閉的時候他不知道,運行時不報錯,怎麼讓客戶端知道,服務器關閉了呢?