
代號:
頁次:
-
四、針對下列 Python 程式碼,依序在兩個 Terminal 執行 server.py 和client.py
後,在 client.py 輸入 Tom 和quit;請說明 client.py 的Terminal 之輸出內
容,並說明 Line 03, 04, 05 程式碼的運作邏輯。(25 分)
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 7000))
s.listen(5)
print('wait for connection...')
while True:
conn, addr = s.accept()
print('connected by ' + str(addr))
indata = conn.recv(1024)
print('recv: ' + indata.decode())
if 'quit' in indata.decode():
outdata = 'bye '
else:outdata = 'hi ' + indata.decode()
conn.send(outdata.encode())
conn.close()
if 'quit' in indata.decode():
break
print('listen...')
s.close()
#client.py
import socket
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 7000))
name = input('>name:')
print('send: ' + name)
s.send(name.encode())
indata = s.recv(1024)
s.close()
print('>' + indata.decode())
if 'quit' in name:
break