搭建TCP伺服器環境和jmeter測試TCP協議
阿新 • • 發佈:2019-01-09
- 搭建伺服器環境
import socket
import sys
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn) :
#Sending message to connected client
conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(1024)
reply = 'OK...' + data
if not data:
break
conn.sendall(reply)
conn.close()
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
- 執行程式
[[email protected] Desktop]# python threadServer.py
Socket created
Socket bind complete
Socket now listening
使用telnet測試連線
[[email protected] dev]# telnet 192.168.1.107 8888
Trying 192.168.1.107...
Connected to 192.168.1.107 (192.168.1.107).
Escape character is '^]'.
Welcome to the server. Type something and hit enter
nihao
OK...nihao
Connection closed by foreign host.
至此tcp伺服器環境已經搭建好了
使用jmeter編寫簡單指令碼進行測試
執行結果
正常結果
這裡出現兩種異常情況,一種是沒有收到返回結果
一種是 Software caused connection abort
出現問題的原因還不清楚,後面分析
增加併發進行壓測的時候能夠明顯看到伺服器CPU上升
到這,jmeter測試TCP協議基本過程講完,重要的還是後面的問題分析和定位。
中途遇到的問題:本地使用telnet能夠傳送請求,使用jmeter卻提示unknownhost 。這是我本地jmeter的問題,重啟下jmeter或者重新開啟jmeter自帶的tcpsampler指令碼,修改一下。就可以運行了。