0

我正在向服务器发送数据,如下所示:

 save(){ 
   var el = this.parent.nodes;
   print(el);print(el.length);
   request = new HttpRequest();
    if(el.length == 1) print('No lines to save!');
     else           
     {        
      var opt = el[i].shadowRoot.nodes[0].options[el[i].shadowRoot.nodes[0].selectedIndex].text;
      print(this.parent.nodes.length);
      for(var i=1; i < el.length; i++)
             {                         
                        orderLines.add({ 
                             'poid': orderHeader[0]['OrderID'],
                            'ponum': orderHeader[0]['onum'],
                            'lnum' : i.toString(),
                           'itmid' :el[i].shadowRoot.nodes[0].value,
                           'icode' : opt,
                              'qty': el[i].shadowRoot.nodes[1].value,
                             'rqty': 0,
                             'bqty': el[i].shadowRoot.nodes[1].value,
                             'iqty': 0,
                            'biqty': el[i].shadowRoot.nodes[1].value,
                            'price': el[i].shadowRoot.nodes[2].value,
                              'rdd': orderHeader[0]['rdd'],
                              'eta': '',
                             'flag': 0 
                                        });  

                        print(orderLines);

                        request.onReadyStateChange.listen(onData_save);   
                        request.open('POST', host+'/sPO');
                        request.send(JSON.encode(orderLines));  
               }
      }
  }

我的服务器端功能是:

void main() {
  connections = new List<WebSocket>();

  HttpServer.bind(HOST, PORT).then((HttpServer server) {
   print('Server listening on port ${PORT}.');
   server.listen((HttpRequest request) {
    if (WebSocketTransformer.isUpgradeRequest(request)) {
      WebSocketTransformer.upgrade(request).then(handleWS); 
    } else gotMSG(request);        
    });
  }); 
}

handleWS(WebSocket ws){

connections.add(ws);
print('Client connected, there are now ${connections.length} client(s) connected.');
ws.listen((String message) {
  for (WebSocket connection in connections) {
  connection.add(message);
  }
},
onDone: () {
 connections.remove(ws);
 print('Client disconnected, there are now ${connections.length} client(s) connected.');
});
}

 void gotMSG(HttpRequest request) {
 switch (request.method) {
  case 'POST': 
    handlePost(request);
    break;
  case 'OPTIONS':
    handleOptions(request);
    break;
  default:
    defaultHandler(request);
 }
}

void serveRequest(HttpRequest request){
  print('Listening for GET and POST on http://$HOST:$PORT');
  request.response.statusCode = HttpStatus.FORBIDDEN;
   request.response.reasonPhrase = "WebSocket connections only";
   request.response.close();  
}

void handlePost(HttpRequest req) {
  HttpResponse res = req.response;
     switch (req.uri.path) {

       case '/login': login(req); break;
       ...
       case '/sPO': savePO(req); break;

       default: break;
     }     
}

如果发送的订单仅为一行,则 /sPO => savePO 执行一次,但如果订单中有 n 行,则该函数执行多次,找不到模式,在 SavePO 我使用 oracledart pub ,所以认为其中有问题,并尝试了 postgresql pub,但得到了相同的结果,savePO 函数是:

void savePO(HttpRequest req){

 HttpResponse res = req.response;
 addCorsHeaders(res);
 print('${req.method}: ${req.uri.path}');

 Future future() => new Future.value(true);

 req.listen((List<int> buffer) {
 var theDataLines = JSON.decode(new String.fromCharCodes(buffer));
 print(theDataLines);
        connect(db).then((conn) {  
          for (var theData in theDataLines)
               conn.execute("""
                      insert into pol 
                             (poid,ponum,lnum,itmid,icode,qty,rqty,bqty,iqty,biqty,price,rdd, eta, flag)
                      values (@poid,@ponum,@lnum,@itmid,@icode,@qty,@rqty,@bqty,@iqty,@biqty,@price,
                              to_timestamp(@rdd,'YYYY-MM-DD'), to_timestamp(@eta,'YYYY-MM-DD'), @flag)
                   """,
                {                     
                      'poid': theData['poid'],
                     'ponum': theData['ponum'],
                     'lnum' : theData['lnum'],
                    'itmid' : theData['itmid'],
                    'icode' : theData['icode'],
                       'qty': theData['qty'],
                      'rqty': theData['rqty'],
                      'bqty': theData['bqty'],
                      'iqty': theData['iqty'],
                     'biqty': theData['biqty'],
                     'price': theData['price'],
                       'rdd': theData['rdd'].toString(),
                       'eta': theData['eta'].toString(),
                      'flag': theData['flag']
                 })
        .then((_)=>conn.query('commit').toList().then((rows) {print('committed');}))
        .then((_){
                    res.write('done');
                    res.close(); 
               });
    });    // END of SQL
  }, onError: printError);  // End of server listen
 }  // END of function

我什至试图改变:

case '/sPO': savePO(req); break;

成为

case '/sPO': print(1); break;

它在发送 6 行订单后打印了 1、4 次!!

4

1 回答 1

0

对我来说很难看到你真正想要完成什么。

问题很可能是您的save()方法。您写了它的行为方式,但对您尝试完成的工作却没有多少?
为什么不将更多行放入一个 JSON 字符串中,然后在一个请求中将它们一起发布?

您创建一个实例并在此实例上重复request调用。您还可以在同一个请求对象上多次注册处理程序,这会导致在事件仅发生一次时被多次调用。sendrequestonReadyStateChangeonData_save

我认为你应该在request = new HttpRequest();之前搬下来

request.open('POST', host+'/sPO');
request.send(JSON.encode(orderLines));  

或者更好地request.onReadyStateChange.listen(onData_save);升级到request = new HttpRequest();,将所有订单添加到一个 JSON 中并调用

request.open('POST', host+'/sPO');
request.send(JSON.encode(orderLines));  

在 for 循环之后。

我看到的另一个问题是你生火然后忘记了。如果发送请求由于某种原因失败怎么办?

我将创建一个返回未来的 sendJSON 方法(带有一个完成器,它在onDone出现completeError问题时完成。

当你想在你的中创建多个请求时,save()你可以使用类似的东西

// create your JSON

var futures = [];
for(i = 0; i < 5; i++) {
  futures.add(sendData(myJson)); // collects the futures returned from sendData
}
// executes all futures and waits for all to respond and then returns another future
return Future.wait()
.then((results) {
  results.forEach((r) {
    // check result
  });
});
于 2014-10-21T08:17:52.553 回答