滿足客戶端與服務端通訊,套接字。
選擇sentence表示客戶端對服務端的請求內容。
client.py
from socket import
*servername =
'192.168.159.135'
serverport =
12000
clientsocket = socket(af_inet, sock_stream)
#新建clientsocket.connect(
(servername,serverport)
)# 分別注釋掉乙個進行測試
# sentence='show me os info'#列印作業系統的資訊
sentence=
'show me disk info'
#列印磁碟資訊
sentence=
input
("give me a order?"
)clientsocket.send(
bytes
(sentence,
'utf-8'))
modifiedsentence = clientsocket.recv(
2048
)# 檢查類別
# print(type(modifiedsentence))
# print(type(modifiedsentence.decode()))
print
('from server:'
+ modifiedsentence.decode())
#列印返回資訊,二進位制先進行解碼
clientsocket.close(
)#關閉
server.py
from socket import
*import os
import shlex, subprocess
serverport =
12000
serversocket = socket(af_inet,sock_stream)
#新建serversocket.bind((''
,serverport)
)serversocket.listen(1)
print
('the server is ready to receive'
)while
true
:try
: connectionsocket, addr = serversocket.accept(
) sentence = connectionsocket.recv(
1024
).decode(
)if sentence==
'show me os info'
:#作業系統資訊
capitalizedsentence = subprocess.check_output(
["cat"
,"/proc/version"
], shell =
false
)#返回標準輸出
# 測試使用
# print(type(capitalizedsentence))
print
(capitalizedsentence)
elif sentence==
'show me disk info'
:#磁碟資訊
capitalizedsentence = subprocess.check_output(
["lsblk"])
# 測試使用
# print(type(capitalizedsentence))
print
(capitalizedsentence)
else
:#其他情況顯示為錯誤
capitalizedsentence=
"wrong input"
print
(capitalizedsentence)
connectionsocket.send(capitalizedsentence.decode(errors=
'replace'
).encode(encoding=
'utf-8'
,errors=
'replace'))
#編碼 connectionsocket.close(
)except keyboardinterrupt:
exit(
"keyboard interrupt"
)#鍵盤終止程式執行
else
:pass
C 服務端與客戶端
c 服務端與客戶端連線實現的由來 那麼既然乙個伺服器端口可以應對多個客戶端連線,那麼接下來我們就看一下,如何讓多個客戶端與服務端連線。如同我們上面所說的,乙個tcpclient就是乙個socket,所以我們只要建立多個tcpclient,然後再呼叫connect 方法就可以了 c 服務端與客戶端連線...
服務端與客戶端互動
搭建伺服器 伺服器端 using system.net.sockets using system.net using system.io using system.text namespace sockerservice endpoint point new ipendpoint ipaddress...
NodeJS TCP客戶端與服務端
server.js var net require net 載入網路模組 var clients 0 建立id來引用連線的每乙個客戶端 var server net.createserver function client client.write welcome client clientid 使...