为什么我的代码数据会丢失

Peter_Parker 2007-12-13 09:33:02
简单实现网络的滑动窗口协议,我用的是线程里的生产者消费者问题,一样解决,但是现在发了数据,只能收到一半的数据,怎么会这样呢?谢谢了,代码在下面!
import java.util.*;
import java.io.*;
class Frames{
String type;
int sequenceNo;
int datasize;
byte data[];
public Frames(String t,int s,byte[] d){
type = t;
sequenceNo = s;
data = d;
}
public String gettype(){
return type;
}
public int getsequenceNo(){
return sequenceNo;
}
public int getdatasize(){
return datasize;
}
public byte[] getdata(){
return data;
}
}
class Send implements Runnable{
Frames inframe;
Frames ackframe;
String s;
Bufferframe buffer;
int nextStart=0;
int windowStart=0;
int windowEnd;
int sequenceN;
byte a[] = new byte[100];
File f=new File("D:\\s\\new.jpg");
FileInputStream in =null;
public Send(Bufferframe b){
buffer = b;
}
public void run(){
try{
in = new FileInputStream(f);
}catch(FileNotFoundException e1){
System.out.println("can not find file");
System.exit(-1);
}
try{
in.read(a);
}catch(IOException e2){
System.out.println("fail");
System.exit(-1);
}

for(int k =0;k<buffer.windowsize;k++){
sequenceN = nextStart;
inframe = new Frames("Information",sequenceN,a);
System.out.println("Creat "+sequenceN+""+inframe.gettype()+" frame");
nextStart=nextStart+1;
buffer.put(inframe);
System.out.println("Send NO."+sequenceN+" frame");
}


try{
in.close();
}catch(IOException e3){}

}
}


class Receive implements Runnable{
byte c[];
Frames inframe;
Frames ackframe;
String s;
Bufferframe buffer;

int windowStart=0;
int windowEnd;
int nextStart=0;
int ackN;
File f = new File("D:\\s\\q.jpg");
FileOutputStream out = null;
public Receive(Bufferframe b){
buffer = b;
}
public void run(){
try{
out = new FileOutputStream(f);
}catch(FileNotFoundException e){
System.out.println("fail");
System.exit(-1);
}
for(int k=0;k<buffer.windowsize;k++){
ackN=nextStart;
ackframe = buffer.get();
System.out.println("Recevie NO."+ackN+" frame");
nextStart=nextStart+1;
c = buffer.get().getdata();
try{
out.write(c);
}catch(IOException e2){}
}
try{
out.close();
}catch(IOException ea){}
}
}
class Bufferframe{
public int windowsize=4;
public int index = 0;
Frames[] arr = new Frames[windowsize];
synchronized void put(Frames f){
while(index == arr.length){
try{
this.wait();
}
catch(InterruptedException e){}
}
this.notify();
arr[index]=f;
index++;
}
synchronized Frames get(){
while(index == 0){
try{
this.wait();
}
catch(InterruptedException e){}
}
this.notify();
index--;
return arr[index];
}
}

public class Assignment{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
// System.out.println("Please enter the size of window");
// int t =input.nextInt();

Bufferframe b=new Bufferframe();
new Thread(new Send(b)).start();
new Thread(new Receive(b)).start();
}
}
...全文
52 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧