我用套接字发送了GET消息.而且我收到了响应消息(字符串).但我想接收为十六进制.但是我没有完成.这是我的代码块作为字符串.你能帮助我吗 ?
dos = new DataOutputStream(socket.getoutputStream()); dis = new BufferedReader(new inputStreamReader(socket.getinputStream())); dos.write(requestMessage.getBytes()); String data = ""; StringBuilder sb = new StringBuilder(); while ((data = dis.readline()) != null) { sb.append(data); }
解决方法:
当您使用BufferedReader时,您将获得String格式的输入..更好的方法来使用inputStream …
这是实现此目的的示例代码.
inputStream in = socket.getinputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] read = new byte[1024]; int len; while((len = in.read(read)) > -1) { baos.write(read, 0, len); } // this is the final byte array which contains the data // read from Socket byte[] bytes = baos.toByteArray();
得到byte []后,可以使用以下函数将其转换为十六进制字符串
StringBuilder sb = new StringBuilder();for (byte b : bytes) { sb.append(String.format("%02X ", b));}System.out.println(sb.toString());// here sb is hexadecimal string
参考来自java-code-to-convert-byte-to-hexadecimal
总结以上是内存溢出为你收集整理的java-如何接收十六进制的套接字输入?全部内容,希望文章能够帮你解决java-如何接收十六进制的套接字输入?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)