zoukankan      html  css  js  c++  java
  • Java 基础 (网络编程 TCP 例子)

    Java 是 Internet上的语言,它从语言级上提供了对网络应用程序的支持,程序员能够很容易开发常见的网络应用程序。

    Java 提供的网络类库,可以实现无痛的网络连接,联网的底层细节被隐藏在 Java 的本机安装系统里,由 JVM 进行控制。并且 Java 实现了一个跨平台的网络库,程序员面对的是一个统一的网络编程环境。

    实现网络中的主机互相通信

    1.通信双方地址

    IP
    端口号

    2.一定的规则 (即:网络通信协议。有两套参考模型)

    OSI 参考模型: 模型过于理想化,未能在因特网上进行广泛推广
    TCP/IP 参考模型(或TCP/IP协议): 事实上的国际标准。

    网络通信协议

    端口分类

    公认端口: 0~1023。被预先定义的服务通信占用(如:HTTP占用端口80,FTP占用端口21,Telnet占用端口23)
    注册端口: 1024~49151。分配给用户进程或应用程序。(如:Tomcat占用端口8080,MySQL占用端口3306,Oracle占用端口1521等)。
    动态/私有端口:49152~65535。

    端口号与IP地址的组合得出一个网络套接字:Socket。

    TCP 和 UDP

    TCP协议
    > 使用TCP协议前,须先建立TCP连接,形成传输数据通道
    > 传输前,采用“三次握手”方式,点对点通信,是可靠的
    > TCP协议进行通信的两个应用进程:客户端、服务端。
    > 在连接中可进行大数据量的传输
    > 传输完毕,需释放已建立的连接,效率低
    
    UDP协议
    > 将数据、源、目的封装成数据包,不需要建立连接
    > 每个数据报的大小限制在64K内
    > 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
    > 可以广播发送
    > 发送数据结束时无需释放资源,开销小,速度快
    

    TCP

    TCPTest1.java

    package com.klvchen.java1;
    
    import org.junit.Test;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class TCPTest1 {
    
        //客户端
        @Test
        public void client(){
            Socket socket = null;
            OutputStream os = null;
            try {
                //1.创建Socket对象,指明服务器端的ip和端口号
                InetAddress inet = InetAddress.getByName("127.0.0.1");
                socket = new Socket(inet, 8899);
                //2.获取一个输出流,用于输出数据
                os = socket.getOutputStream();
                //3. 写出数据的操作
                os.write("你好,我是客户端mm".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //4.资源的关闭
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
            }
    
        }
    
        //服务器
        @Test
        public void server(){
    
            ServerSocket ss = null;
            Socket socket = null;
            InputStream is = null;
            ByteArrayOutputStream baos = null;
            try {
                //1.创建服务器端的ServerSocket,指明自己的端口号
                ss = new ServerSocket(8899);
                //2.调用accept()表示接收来自于客户端的socket
                socket = ss.accept();
                //3.获取输入流
                is = socket.getInputStream();
    
                // 不建议这样写,可能会有乱码
                //byte[] buffer = new byte[20];
                //int len;
                //while ((len = is.read(buffer)) != -1) {
                //    String str = new String(buffer, 0, len);
                //    System.out.println(str);
                //}
                //4.读取输入流中的数据
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[5];
                int len;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0 , len);
                }
    
                System.out.println(baos.toString());
    
                System.out.println("收到来自于:" + socket.getInetAddress().getHostAddress() + "的数据");
            } 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 (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (ss != null) {
                    try {
                        ss.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
    
    
    
        }
    
    }
    

    TCPTest2.java

    package com.klvchen.java1;
    
    import org.junit.Test;
    
    import java.io.*;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /*
    客户端发送文件给服务端,服务端将文件保存在本地
     */
    public class TCPTest2 {
    
        @Test
        public void client() throws IOException {
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
    
            OutputStream os = socket.getOutputStream();
    
            FileInputStream fis = new FileInputStream(new File("1.png"));
    
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
    
            fis.close();
            os.close();
            socket.close();
        }
    
        @Test
        public void server() throws IOException{
            ServerSocket ss = new ServerSocket(9090);
    
            Socket socket = ss.accept();
    
            InputStream is = socket.getInputStream();
    
            FileOutputStream fos = new FileOutputStream(new File("4.png"));
    
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
    
            fos.close();
            is.close();
            socket.close();
            ss.close();
        }
    }
    
    

    TCPTest3.java

    package com.klvchen.java1;
    
    import org.junit.Test;
    
    import java.io.*;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /*
    从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。
    
     */
    public class TCPTest3 {
        @Test
        public void client() throws IOException {
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
    
            OutputStream os = socket.getOutputStream();
    
            FileInputStream fis = new FileInputStream(new File("1.png"));
    
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
    
            socket.shutdownOutput();
    
            //接收来自于服务器端的数据,并显示到控制台上
            InputStream is = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bufferr = new byte[1024];
            int len1;
            while ((len1 = is.read(bufferr)) != -1) {
                baos.write(bufferr,0,len1);
            }
    
            System.out.println(baos.toString());
    
            fis.close();
            os.close();
            socket.close();
            baos.close();
            is.close();
        }
    
        @Test
        public void server() throws IOException{
            ServerSocket ss = new ServerSocket(9090);
    
            Socket socket = ss.accept();
    
            InputStream is = socket.getInputStream();
    
            FileOutputStream fos = new FileOutputStream(new File("4.png"));
    
            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();
            ss.close();
            os.close();
    
        }
    }
    
  • 相关阅读:
    JavaScript或jQuery模拟点击超链接和按钮
    web开发中目录路径问题的解决
    jQuery操作复选框的简单使用
    php中常用魔术方法的举例
    Code-Validator:验证经度、验证维度
    Code-Validator:验证身份证号
    Code-Validator:验证IPv6地址
    Code-Validator:验证IPv4地址
    Code-Validator:验证网址(可以匹配IPv4地址但没对IPv4地址进行格式验证;IPv6暂时没做匹配)
    Code-Validator:验证电子邮箱
  • 原文地址:https://www.cnblogs.com/klvchen/p/15518576.html
Copyright © 2011-2022 走看看