服務(wù)器端:
import socket
import time
import threading
host = socket.gethostname()
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 創(chuàng)建socket (AF_INET:IPv4, AF_INET6:IPv6) (SOCK_STREAM:面向流的TCP協(xié)議)
s.bind((host,port)) # 綁定本機IP和端口(>1024)
s.listen(1) # 監(jiān)聽佳簸,等待連接的最大數(shù)目為1
print('Server is running...')
def TCP(sock, addr): # TCP服務(wù)器端處理邏輯
print('Accept new connection from %s:%s.' % addr) # 接受新的連接請求
while True:
data = sock.recv(1024) # 接受其數(shù)據(jù)
time.sleep(1) # 延遲
if not data or data.decode() == 'quit': # 如果數(shù)據(jù)為空或者'quit'乙墙,則退出
break
sock.send(data.decode('utf-8').upper().encode()) # 發(fā)送變成大寫后的數(shù)據(jù),需先解碼,再按utf-8編碼, encode()其實就是encode('utf-8')
sock.close() # 關(guān)閉連接
print('Connection from %s:%s closed.' % addr)
while True:
sock, addr = s.accept() # 接收一個新連接
t = threading.Thread(target=TCP, args=(sock, addr))
t.start()
客戶端:
import socket
host = socket.gethostname()
port = 12345
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #創(chuàng)建一個socket
s.connect((host, port)) #建立連接
while True: #接受多次數(shù)據(jù)
data = input('請輸入要發(fā)送的數(shù)據(jù):') #接收數(shù)據(jù)
if data == 'quit': #如果為'quit',則退出
break
s.send(data.encode()) #發(fā)送編碼后的數(shù)據(jù)
print(s.recv(1024).decode('utf-8')) #打印接收到的大寫數(shù)據(jù)
s.send(b'quit') #放棄連接
s.close() #關(guān)閉socket