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(4090));
            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[0] = (byte) (n & 0xff);
        b[1] = (byte) (n >> 8 & 0xff);
        return b;
    }

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


}

你可能感兴趣的:(java,java,开发语言)