TCP网络编程一

服务端

public class Server {
    public static void main(String[] args) throws IOException {
        //本机9999端口接听,等待链接
        ServerSocket serverSocket = new ServerSocket(9527);
        //无客户端连接时处于阻塞状态
        System.out.println("服务端等待监听。。。");
        Socket socket = serverSocket.accept();
        System.out.println("服务端" + serverSocket.getClass());
        InputStream inputStream = socket.getInputStream();

        byte[] b = new byte[1024];
        int read = 0;
        while ((read = inputStream.read(b) )!= -1){
            System.out.println(new String(b,0,read));
        }

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello client".getBytes());
        //socket.shutdownOutput();

        inputStream.close();
        outputStream.close();
        socket.close();
        serverSocket.close();
    }
}

客户端

public class CLient {
    public static void main(String[] args) throws IOException {
        InetAddress localHost = InetAddress.getLocalHost();
        Socket socket = new Socket("127.0.0.1", 9527);
        System.out.println("客户端" + socket.getClass());

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello server".getBytes());
        //通知对方自己写完了,可以读取了,如果不加服务端和客户端会出现阻塞
        socket.shutdownOutput();

        //读
        InputStream inputStream = socket.getInputStream();
        byte[] b = new byte[1024];
        int readLen = 0;
        while ((readLen = inputStream.read(b)) != -1){
            System.out.println(new String(b, 0, readLen));
        }

       /* inputStream.close();
        outputStream.close();
        socket.close();*/
        System.out.println("客户端退出。。。");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值