Python socket模塊實現TCP服務端客戶端
寫了詳細的註釋,若是有哪一行不明白,可留言哦。
服務端腳本
# _*_ coding: utf-8 _*_
__author__ = 'xiaoke'
__date__ = '2018/6/13 14:39'
# 這個腳本建立一個TCP服務器,它接收來自客戶端的消息,而後將消息加上時間戳前綴並返回客戶端
import socket
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ = 4096
ADDR = (HOST, PORT)
# 建立TCP套接字
tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 建立UDP套接字
# udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tcpSock.bind(ADDR) # 將地址綁定到套接字上
tcpSock.listen(5) # 設置並啓動TCP監聽器
while True:
print("waiting for connection....")
tcpCliSock, addr = tcpSock.accept() # 被動接收TCP客戶端鏈接,一直等待直到鏈接到達(阻塞)
print("... connected from", addr)
while True:
data = tcpCliSock.recv(BUFSIZ) # 接收TCP消息
# print(data)
# 若是有數據加上時間戳後返回給客戶端,由於只接受字節數據,因此把數據使用bytes函數轉換
if not data:
break
tcpCliSock.send(bytes('[%s] %s' % (ctime(), data.decode('utf-8')), 'utf-8'))
tcpCliSock.close()
# tcpSock.close()
客戶端腳本
# _*_ coding: utf-8 _*_
__author__ = 'xiaoke'
__date__ = '2018/6/13 16:01'
import socket
import sys
HOST = '127.0.0.1'
PORT = 21567
BUFSIZ = 4096
ADDR = (HOST, PORT)
# 建立客戶端TCP鏈接
tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 鏈接服務器
try:
tcpCliSock.connect(ADDR)
except Exception as e:
print("鏈接服務器失敗:",e)
sys.exit(-1)
while True:
data = input('> ')
if not data:
break
# 循環發送數據,直到沒有數據發送退出
tcpCliSock.send(bytes(data, encoding='utf-8'))
# 接收服務端返回的消息,若是沒有消息返回,也將退出循環
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()