Socket与Server通讯

 制定消息头,消息体格式

ByteArrayOutputStream 对byte类型数据进行写入的类 ,自动扩容,相当于一个中间缓冲层,将类写入到文件等其他outputStream。它是对字节进行操作,属于内存操作流


import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketUtils {
    private final static String ip = "127.0.0.1";
    private final static int port = 12345;
    private final static int timeout = 5000;

    public static void sendMsg() {
        Socket clientSocket = null;
        try {
            clientSocket = new Socket();
            //连接上后,生成Socket
            clientSocket.connect(new InetSocketAddress(ip, port),timeout);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            outputStream.write(intToBytesToLH4(100));
            outputStream.write(intToBytesToLH2(2));
            outputStream.write(intToBytesToLH2(2));
            outputStream.write(intToBytesToLH4(1));
            byte[] b = new byte[16];
            System.arraycopy("".getBytes(), 0, b, 0, "".getBytes().length);
            b["".getBytes().length] = 0;
            outputStream.write(b);
            socket关联的输出流对象
            OutputStream outputStream1 = clientSocket.getOutputStream();
            //将缓冲区的数据全部获取出来,返回字节数组
            byte[] c = outputStream.toByteArray();
            //通过输出流,写入数据到数据通道
            outputStream1.write(c);
            //清空缓存并输出流
            outputStream1.flush();
            //关闭流对象
            outputStream1.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭客户端Socket连接
            try {
                clientSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 将int转为高字节在前,低字节在后的byte数组
    private static byte[] intToBytesToLH2(int n) {
        byte[] b = new byte[2];
        b[1] = (byte) (n & 0xff);
        b[0] = (byte) (n >> 8 & 0xff);
        return b;
    }

    private static byte[] intToBytesToLH4(int n) {
        byte[] b = new byte[4];
        b[3] = (byte) (n & 0xff);
        b[2] = (byte) (n >> 8 & 0xff);
        b[1] = (byte) (n >> 16 & 0xff);
        b[0] = (byte) (n >> 24 & 0xff);
        return b;
    }


}

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值