现在服务器发送代码: public int Sendbytes(byte [] bytes)//待发数据在数组中 { int bytesSent=0; int page, n,k,t; n = bytes.Length; int sendtimes = 1;//连续发送次数sendtimes=1,若设为10表示发10个包再确认一次 int sendbytes=1000;//每次发送数据大小 page = 0; //发送页面 byte[] sendbuf = new byte[sendbytes + 8];//发送缓冲区 int off0,off, l;// off:偏移量 l:数据长度, //发送缓冲区格式: 数据长度(4字节),数组偏移量(4字节),发送数据(1000) byte[] bsize; byte[] boff; string sre; bool sendover = false;//发送结束标志 while (true) { page++; //发送 第一个页面 page=1 t = 0;//设置重复发送次数,若重复发送3次还是没有收到客户端确认,就退出发送过程 while (true) { t++; k = 0; off0 = (page - 1) * sendtimes * sendbytes;//每次发送一个页面的起始偏移量 while (k < sendtimes) { off = off0 + k * sendbytes; //数据所在数组缓冲区偏移位置(索引) if (off < n - sendbytes)//本次发送后,还有待发数据 l = sendbytes;//l 表示发送数据大小,如1000, else if (off == n - sendbytes)//本次刚好发送完成 { l = sendbytes; sendover = true; //发送结束标志为真 } else if (off >= n) { //发送完毕 l = 0; sendover = true; break; } else { l = n - off;//发送最后少于1000的数据 sendover = true; } //将数据大小,数组偏移量,实际数据写入发送缓冲区 bsize = BitConverter.GetBytes(l); boff = BitConverter.GetBytes(off); bsize.CopyTo(sendbuf, 0); boff.CopyTo(sendbuf, 4); Array.Copy(bytes, off, sendbuf, 8, l); try { bytesSent = handle.Send(sendbuf ); } catch { } k++; }//(k < sendtimes) //等待接受确认,接收4个子节的确认数据,等待时间为3秒 sre = Receivedata(4, 3); if (sre == "1234" ||t>5) //收到了确认,或重发了3次,可能客户端退出了 break; }//while (true) 重新发送一个页面的所有记录 if (sendover) break; }//while (true) return 1; }
补充:在局域网测试没有问题,服务器在外网就有问题。 以前服务器发送数据很简单:如下 bytesSent = handle.Send(sendbuf ); 客户端也可收到,后来服务器所在网络升级了,数据一大就丢失,好像数据大于1024X10 就不行了。 后来服务器改为分段发送,每次发送1024+8个字节,然后等待客户端回应,收到回应后发下一个1024+8的数据,可是到了第10次,还是收不到数据,不知为何?
110,526
社区成员
642,571
社区内容
加载中
让您成为最强悍的C#开发者
试试用AI创作助手写篇文章吧