标签:
前几天,模拟了一个tcp发送与接收16进制的小程序。由于需求的改变现在需要接收二进制流式数据,下面记录一下客户端接收数据的实现的源码。
package client;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class ClientSocket {
static Socket socket = null;
static InputStream in = null;
public final static transient byte DL_A0 = (byte) 0xa0;//自定义“协议”分割符
public final static transient byte DL_AF = (byte) 0xaf;
public static void main(String[] args) {
try{
socket = new Socket("127.0.0.1", 8080);
in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
/*根据分隔符定位开始标记--start*/
while (dis.available()>0) {
if (dis.readByte() == DL_AF) {
break;
}
}
/*根据分隔符定位开始标记--end*/
int count = 0; //记录接收一组数据的个数
int ecount = 0;
Short[] temp = new Short[4];
/*定义存放转换后8组x1、y1、x2、y2数据的数组--start*/
int[] x1Array = new int[8];
int[] y1Array = new int[8];
int[] x2Array = new int[8];
int[] y2Array = new int[8];
/*定义存放转换后8组x1、y1、x2、y2数据的数组--end*/
while (true){//dis.available()方法当网络情况不是很好的情况下,很可能获取到的值是0,导致不能进入while循环。采用休眠1s的方法的话可以进入,但是也不能如期望的那样进行循环。此处需要做根据实际情况来。
count++;
temp[count - 1] =dis.readShort();
if (count == 4) {
ecount++; //下一组数据
x1Array[ecount - 1] = temp[0];
y1Array[ecount - 1] = temp[1];
x2Array[ecount - 1] = temp[2];
y2Array[ecount - 1] = temp[3];
dis.skipBytes(2);
if (ecount == 8) {
//TODO 各组数据处理
for (int i = 0; i < 8; i++) {
System.out.println("x1:" + x1Array[i]);
System.out.println("y1:" + y1Array[i]);
System.out.println("x2:" + x2Array[i]);
System.out.println("y2:" + y2Array[i]);
}
ecount = 0;
}
count = 0;
}}}catch(IOException e){
e.printStackTrace();
}finally{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
标签:
原文地址:http://blog.csdn.net/wj512416359/article/details/42496423