网络编程

传输层的两种协议:

  TCP:建立连接后需三次握手确定后才开始进行通信(数据量可以很大),而后四次挥手断开连接。可靠性高但是开销大,                      速度较慢。

  UDP:不需建立连接直接发送数据报(数据量有限制),可靠性低但是开销小,速度快。

TCP:

复制代码
@Test
    public void client() {
        Socket socket = null;
        OutputStream outputStream = null;
        try {
            //1.创建Socket对象,指明服务器端IP和端口号
            InetAddress inetAddress = InetAddress.getByName("192.168.124.12");
            socket = new Socket(inetAddress,7788);
            //2.获取输出流,用于输出数据
            outputStream = socket.getOutputStream();
            //3.写出数据
            outputStream.write("这可不能乱码".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void server() {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1.创建服务器端的ServerSocket,指明自己的端口号
            serverSocket = new ServerSocket(7788);
            //2.调用accept(),接收来自客户端的socket
            accept = serverSocket.accept();
            //3.获取输入流
            is = accept.getInputStream();
            //4.读取输入流的数据
            //使用ByteArrayOutputStream,它会先把字节数组写入自己的一个数组中,写完之后再转化为Srting的话就不会乱码
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer,0,len);
            }

            System.out.println("收到来自于" + accept.getInetAddress().getHostAddress()
                + ":" + baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            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();
                }
            }
        }
    }
复制代码

例:客户端向服务端发送照片,服务端将照片保存并将反馈信息发给客户端

复制代码
@Test
    public void test1() {
        Socket socket = null;
        FileInputStream fis = null;
        OutputStream os = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //创建Socket对象
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            socket = new Socket(ip,7979);
            //将照片写出
            fis = new FileInputStream("tcp.jpg");
            os = socket.getOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes,0,len);
            }
            System.out.println("文件传输完成");
            socket.shutdownOutput();
            //获取反馈信息
            is = socket.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer);
            }
            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 (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test2() {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        FileOutputStream fos = null;
        OutputStream os = null;
        try {
            //创建ServerSocket对象
            serverSocket = new ServerSocket(7979);
            //将接收的照片保存
            accept = serverSocket.accept();
            is = accept.getInputStream();
            fos = new FileOutputStream("tcpbak.jpg");
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes,0,len);
            }
            //发送反馈信息
            os = accept.getOutputStream();
            os.write("照片已收到".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.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();
                }
            }
        }
    }
复制代码

UDP:

复制代码
package io;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

public class UdpTest {

    //发送端
    @Test
    public void sender() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();
            byte[] data = "以UDP方式发送导弹".getBytes();
            InetAddress ip = InetAddress.getByName("127.0.0.1");
            DatagramPacket datagramPacket = new DatagramPacket(data, 0, data.length, ip, 8899);
            socket.send(datagramPacket);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }

    //接收端
    @Test
    public void receiver() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(8899);

            byte[] bytes = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length);
            socket.receive(datagramPacket);
            String str = new String(datagramPacket.getData(),0,datagramPacket.getLength());
            System.out.println(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }
}
复制代码

 

 

 

  

 

posted @   Java厨师长  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示