猿问

泛洪速度过快时服务器无法解析数据包

这是我每秒用太多数据包淹没服务器时得到的错误:


2014/11/28 12:52:49 main.go:59: loading plugin: print

2014/11/28 12:52:49 main.go:86: starting server on 0.0.0.0:8080

2014/11/28 12:52:59 server.go:15: client has connected: 127.0.0.1:59146

2014/11/28 12:52:59 server.go:43: received data from client 127.0.0.1:59146: &main.Observation{SensorId:"1", Timestamp:1416492023}

2014/11/28 12:52:59 server.go:29: read error from 127.0.0.1:59146: zlib: invalid header

2014/11/28 12:52:59 server.go:18: closing connection to: 127.0.0.1:59146

它设法解码一个数据包(有时,可能是 2 或 3 个)然后出错。这是进行泛洪的代码:


import socket

import struct

import json

import zlib

import time


def serialize(data):

    data = json.dumps(data)

    data = zlib.compress(data)


    packet  = struct.pack('!I', len(data))

    packet += data


    return len(data), packet


message = {

    'sensor_id': '1',

    'timestamp': 1416492023,

}


length, buffer = serialize([message])


client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


client.connect(('127.0.0.1', 8080))


while True:

    client.send(buffer)


    #time.sleep(0.0005)

当我取消对time.sleep()调用的注释时,服务器工作正常。似乎每秒太多的数据包正在杀死服务器。为什么?


这是相关的 Go 代码。连接处理程序:


func (self *Server) handleConnection(connection net.Conn) {

    for {

        connection.SetReadDeadline(time.Now().Add(30 * time.Second))


        observations, err := self.Protocol.Unserialize(connection)


        if err != nil {

            log.Printf("read error from %s: %s\n", connection.RemoteAddr(), err)


            return

        }

}

这是反序列化程序:


// Length Value protocol to read zlib compressed, JSON encoded packets.

type ProtocolV2 struct{}


func (self *ProtocolV2) Unserialize(packet io.Reader) ([]*Observation, error) {

    var length uint32


    if err := binary.Read(packet, binary.BigEndian, &length); err != nil {

        return nil, err

    }


    buffer := make([]byte, length)

    rawreader := bufio.NewReader(packet)


    if _, err := rawreader.Read(buffer); err != nil {

        return nil, err

    }


手掌心
浏览 222回答 1
1回答
随时随地看视频慕课网APP

相关分类

Go
我要回答