streamh
发贴: 1
积分: 0
|
于 2007-11-16 10:11
大家好! 本人初学J2ME,在做client和server通信的时候遇到一个收发数据的问题。Server不断地往client端发送图像数据,每个图像数据前面有一个四个字节的包头,标明图像的大小,然后通过TCP往client不停的发不同的图像数据。 client端通过一个while循环,不断的解析,接收,程序如下:
public int revImageData() { try { int v_ret; v_ImageDate = new Vector();
//建立连接 String server = "socket://1723.16.123.231:4150"); byte[] imageData ;//图像数据 byte[] buf = null; //包头信息 int count = 0;
SocketConnection sock = (SocketConnection)Connector.open(server.toString(),Connector.READ); DataInputStream inStream = sock.openDataInputStream();
while(true) { buf = new byte[4]; count = inStream.read( buf,0, buf.length); if ( (count == 4) && (buf != null) ) { dataLength = bytes2int(buf); //先收4个字节,bytes2int函数解析出数据包长度 }
//receive the image data imageData = new byte[dataLength ]; count = inStream.read(imageData,0,imageData.length); //接下来处理收到的图像数据,不用管 ImageDataStore imageObj = new ImageDataStore(imageData); this.v_ImageDate.addElement(imageObj); //放到一个vector中 }//end while return 1; } catch(Exception e_exp1) { System.out.println(e_exp1.toString()); return 43; } }
在这里出现的问题是:前面N幅图像都是完整地收到的,但是再次进行第N+1次循环的时候,dataLength就错了,是个很大的数值(由server端可知是个错误的值,把buf里面的内容打出来跟server对比,可知收到的buf就是已经错了,问题不在解析那)。而这个N值是不定的;
这段程序有什么问题么?接收大量的数据该如何处理为好? 想了很久,没想明白是怎么回事,望各位不吝赐教!!!
|