栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何通过TCP连接发送字节数组(java编程)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何通过TCP连接发送字节数组(java编程)

Java中的

InputStream
OutputStream
类本机处理字节数组。您可能要添加的一件事是消息开头的长度,以便接收方知道期望多少字节。我通常喜欢提供一种方法,该方法可以控制字节数组中要发送的字节,这与标准API十分相似。

像这样:

private Socket socket;public void sendBytes(byte[] myByteArray) throws IOException {    sendBytes(myByteArray, 0, myByteArray.length);}public void sendBytes(byte[] myByteArray, int start, int len) throws IOException {    if (len < 0)        throw new IllegalArgumentException("Negative length not allowed");    if (start < 0 || start >= myByteArray.length)        throw new IndexOutOfBoundsException("Out of bounds: " + start);    // Other checks if needed.    // May be better to save the streams in the support class;    // just like the socket variable.    OutputStream out = socket.getOutputStream();     DataOutputStream dos = new DataOutputStream(out);    dos.writeInt(len);    if (len > 0) {        dos.write(myByteArray, start, len);    }}

编辑 :要添加接收方:

public byte[] readBytes() throws IOException {    // Again, probably better to store these objects references in the support class    InputStream in = socket.getInputStream();    DataInputStream dis = new DataInputStream(in);    int len = dis.readInt();    byte[] data = new byte[len];    if (len > 0) {        dis.readFully(data);    }    return data;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/497640.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号