Socket client = new Socket("192.168.1.22", 8217);
client.setSoTimeout(10000);
int i;
String stra = "7e8004003c000079676a202020202020203132333435362020202020202020202020202020202020202020202020202020202020202020202020202020202020202020eb7e";
byte[] strm = BytesToHexString.hexString2Bytes(stra);
System.out.println(strm);
//获取Socket的输出流,用来发送数据到服务端
PrintStream out = new PrintStream(client.getOutputStream());
//获取Socket的输入流,用来接收从服务端发送过来的数据
BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
DataInputStream in = new DataInputStream(client.getInputStream());
byte[] temp= new byte[1024];
byte[] temp1;
char[] cha= new char[200];
//CharArrayReader reader = new CharArrayReader(client.getInputStream());
boolean flag = true;
boolean sendflag = true;
while(flag){
if(sendflag){
System.out.print("发送数据给服务端");
//发送数据到服务端
out.write(strm);
sendflag=false;
}
try{
i=in.read(temp);
String b = BytesToHexString.bytes2HexString(temp);//字节数组转16进制字符串
System.out.println("111111111111111111===="+b);
}catch(SocketTimeoutException e){
System.out.println("Time out, No response");
}
}
//input.close();
if(client != null){
//如果构造函数建立起了连接,则关闭套接字,如果没有建立起连接,自然不用关闭
client.close(); //只关闭socket,其关联的输入输出流也会被关闭
}
}
i=in.read(temp);这里会获取服务端发过来的数据,源源不断。而且上一条收到的temp可能要与下一条的temp连接起来数据才完整,求大牛指点一点。第一次接触socket
------解决思路----------------------
你这问题不清楚,得说明白点
从inputStream读数据的时候,通常都是循环处理,保证读的数据完整,除非你确定每次数据不超过你定义的1024个字节
------解决思路----------------------
或者有能判断是一句的唯一判断,这样你可以读出来存到一个list或者map里面,然后通过这个唯一判断去拼接上下两句
------解决思路----------------------
两边要定协议,否则你是无法理解你究竟收到了什么。
参考:
Apache Mina使用JSON数据进行通信的使用方法
http://www.csdn123.com/html/exception/688/688547_688542_688545.htm