我的服务器上运行了以下示例代码。它只是接受连接,当它读取它立即响应的内容时:
import socket
import select
def main():
bind = ("0.0.0.0", 28889)
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(bind)
server_socket.listen(50)
server_socket.setblocking(0)
server_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
clients = {}
epoll = select.epoll() # @UndefinedVariable
epoll.register(server_socket.fileno(), select.EPOLLIN) # @UndefinedVariable
while 1:
events = epoll.poll(1)
for (fileno, event) in events:
if fileno == server_socket.fileno():
sock, addr = server_socket.accept()
sock.setblocking(0)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
fileno = sock.fileno()
epoll.register(fileno, select.EPOLLIN) # @UndefinedVariable
clients[fileno] = sock
elif event & select.EPOLLIN: # @UndefinedVariable
sock = clients[fileno]
try:
sock.recv(4096)
sock.send("~\n")
except socket.error:
sock.close()
del clients[fileno]
elif event & select.EPOLLHUP: # @UndefinedVariable
sock = clients[fileno]
sock.close()
del clients[fileno]
if __name__ == "__main__":
main()
我有以下客户端代码连接到服务器并将响应时间乘以 10 倍:
import socket
import time
def main():
sock = socket.socket()
sock.connect(("192.30.35.15", 28889))
for _ in xrange(10):
start_time = time.time()
sock.send("~\n")
sock.recv(2048)
end_time = time.time()
print "Ping: %.5f" % (end_time-start_time)
if __name__ == "__main__":
main()
这是我运行它得到的结果:
Ping: 0.09100
Ping: 0.11500
Ping: 0.87100
Ping: 0.24400
Ping: 0.49100
Ping: 1.45300
Ping: 0.74800
Ping: 1.59100
Ping: 0.43600
Ping: 0.27100
这似乎很糟糕,ping 跳到 1.5 秒。
这是我 ping 服务器时得到的结果:
Reply from 192.30.35.15: bytes=32 time=83ms
为什么我的响应时间如此糟糕,我可以做些什么来改善它?
注意:这是一个便宜的租用服务器,它是我能期待的最好的吗?我对服务器管理不太了解,有什么需要检查的吗?