JAVA网络编程 TCP

摘自 b站尚硅谷JAVA视频教程

 

客户端:

Socket socket = null;
        OutputStream os = null;
        try {
            InetAddress cliIP =  InetAddress.getByName("127.0.0.1");
            socket = new Socket(cliIP, 9090);
            os = socket.getOutputStream();
            os.write("你好呀".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(os!=null)
                    os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
View Code

 

服务器端

 ServerSocket ss = null;
        Socket cli = null;
        InputStream is = null;
        ByteArrayOutputStream bais = null;
        try {
            ss = new ServerSocket(9090);
            cli = ss.accept();
            is = cli.getInputStream();
            bais = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len =0;
            while((len=is.read(buf))!=-1){
                bais.write(buf,0,len);
            }
            System.out.println(bais.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bais!=null)
                    bais.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (is!=null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (cli!=null)
                    cli.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ss!=null)
                    ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
View Code

 

知识点: ByteArrayOutputStream的使用

 

posted @ 2020-02-22 10:58  超级学渣渣  阅读(152)  评论(0编辑  收藏  举报