首页 > 编程语言 >Java 网络编程(五)TCP

Java 网络编程(五)TCP

时间:2022-11-22 16:00:57浏览次数:37  
标签:Java socket 编程 TCP baos new close null os

客户端

  1.连接服务器socket

  2.发送消息

//客户端
public class TcpClientDemo01 {
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.要知道服务器的地址,端口号
            InetAddress serverIp = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //2.创建一个socket连接
            socket = new Socket(serverIp,port);
            //3.发送消息 IO流
            os = socket.getOutputStream();
            os.write("你好,欢迎您!".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

  

服务器

  1.建立服务端口ServerSocket

  2.等待用户的连接accept

  3.接受用户的消息

//服务端
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.我得有一个地址
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接过来
            accept = serverSocket.accept();
            //3.读取客户端的消息
            is = accept.getInputStream();
            //管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            if(baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (accept != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

  

文件上传

客户端

public class TcpClientDemo02 {
    public static void main(String[] args) throws Exception{
        //1.创建一个Socket连接
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
        //2.创建一个输出流
        OutputStream os = socket.getOutputStream();
        //3.读取文件
        FileInputStream fis = new FileInputStream(new File("a.jpg"));
        //4.写出文件
        byte[] buffer = new byte[1024];
        int len;
        while((len=fis.read(buffer))!=-1){
            os.write(buffer,0,len);
        }
        //通知服务器我已经结束了
        socket.shutdownOutput();//我已经传输完了
        
        //确定服务器接收完毕才能够断开连接
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
       byte[] buffer2 = new byte[1024];
       int len2;
       while((len2 = inputStream.read(buffer2)) != -1){
           baos.write(buffer2,0,len2);
       }

        System.out.println(baos.toString());

        //5.关闭资源
        baos.close();
       inputStream.close();
        fis.close();
        os.close();
        socket.close();
    }
}

  服务端

public class TcpServerDemo02 {
    public static void main(String[] args) throws Exception{
        //1.创建服务
        ServerSocket serverSocket = new ServerSocket(9000);
        //2.监听客户端的连接
        Socket socket = serverSocket.accept();//阻塞式监听,会一直等待客户端连接
        //3.获取输入流
        InputStream is = socket.getInputStream();
        //4.文件输出
        FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));
        byte[] buffer = new byte[1024];
        int len ;
        while ((len = is.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }
        //通知客户端接收完毕
        OutputStream os = socket.getOutputStream();
        os.write("我接收完毕,你可以断开了".getBytes());

        //关闭资源
        fos.close();
        is.close();
        socket.close();
        serverSocket.close();
    }
}

  

 

 

Tomcat

服务端

  ·自定义S

  ·Tomcat服务器S

客户端

  ·自定义C

  ·浏览器B

 

标签:Java,socket,编程,TCP,baos,new,close,null,os
From: https://www.cnblogs.com/zhulei118/p/16915379.html

相关文章

  • Java FreeMarker模板引擎注入深入分析
    0x01前言最近和 F1or 大师傅一起挖洞的时候发现一处某CMSSSTI的0day,之前自己在复现jpress的一些漏洞的时候也发现了SSTI这个洞杀伤力之大。今天来好好系统学习......
  • 小新学Java10
    栈:先进后出队列:先进先出数组:查询快,增删慢 链表:查询慢、增删快 红黑树: 1、HashSet集合存储数据的结构(哈希表)  2、Set集合存储元素不重复的原理  3、E......
  • Java基础面试题
     ArrayList和LinkedList有什么区别?可以从它们的底层数据结构、效率、开销进行阐述哈ArrayList是数组的数据结构,LinkedList是链表的数据结构。随机访问的时候,Array......
  • Java 网络编程(四)通信协议
    协议:约定,就好比我们现在说的是普通话网络通信协议:速率,传输码率,代码结构,传输控制......TCP/IP协议簇实际上是一组协议重要:1.TCP:用户传输协议2.UDP:用户数......
  • CompletableFuture异步编程
    1、创建/***publicstatic<U>CompletableFuture<U>supplyAsync(Supplier<U>supplier){..}*publicstatic<U>CompletableFuture<U>supplyAsync(Suppl......
  • 【Core Java Volume1】重写equals,hashCode,toString方法
    1重写equals()方法:例:重写父类Employee3的equals方法//重写equals//1显示命名参数otherObject,稍后转化为otherpublicbooleanequals(ObjectotherObject){//2检......
  • 【Mybatis】java.lang.IllegalArgumentException: Mapped Statements collection does
    【java.lang.IllegalArgumentException:MappedStatementscollectiondoesnotcontainvalueforcom.myba】错误一般是有以下四个原因造成:1、mapper.xml中没有加入names......
  • Mybatis学习中遇到的错误java.sql.SQLException: Illegal mix of collations (latin1_
    在Mybatis学习存储过程调用的时候,老是出现【java.sql.SQLException:Illegalmixofcollations(latin1_swedish_ci,IMPLICIT)and(utf8_general_ci,COERCIBLE)foropera......
  • 【Core Java Volume 5】集合算法---查找数组、集合最大值的通用方法
    一、查找数组的最大值1 笔试的时候通常查找数组的最大值,数组类型通常是int类型,可以这样直接写出getMax()代码://数组(int类型)publicstaticintgetMax(int[]nums){......
  • 【Core Java Volume 6】集合算法--二分查找法
    在数组中查找一个对象,当数组是有序的时候可以采用二分查找法。即可以直接查看位于数组中间的元素,看一看是否大于查找的元素。如果大于,用同样的方法在数组的前半部分继续查找......