JAVA---网络编程

InetAddressDemo

/**
 *  解决的两个问题:
 *      如何准确的定位网路上一台或者多台主机;定位主机上的特定的应用
 * 	    找到主机后如何进行可靠的高效率的进行数据的传输
 *
 * 	网络编成的要素:
 * 	    通信双方地址:
 * 	    IP
 * 		端口号
 * 	一定的规则(即:网络通信协议,TCP/IP参考模型(应用型、传输型、应用型、对话型、网络型、物理加数据链表型))
 * 		OSI模型:模型过于理想化
 * 		TCP/IP模型:事实上的国际标准
 *
 * 	通信的要素一:
 * 	    唯一的标识Internet上的计算机(通信实体)
 * 	1   本地回环地址(hostAddress)127.0.0.1 上机名(hostName):localhost
 * 	2   IP地址分类方式一:IPV4和IPV6
 * 	3    IP地址分类方式二:公王地址(万维网使用)和私有地址(局域网使用)。192.168.开头的就是私有地
 *
 *
 * 	域名:
 * 	    www.baidu.com
 *
 * 	    5.本地回路地址:127.0.0.1 对应者:localhost
 *
 * 	    6.如何实例化InetAddress:两个方法:getByName(String host).getLocalHost
 *
 * 	    l两个常用的方法:getHostName()/getHostAddress()
 *
 *
 * 	 7.端口号:
 * 	   要求: 不同的进程有不同的端口号
 * 	   范围: 被规定的一个位整数:0~65535
 */

public class InetAddressTest {
    public static void main(String[] args) {
        try {
            //创建对象,对应的IP地址
            InetAddress inet1    =InetAddress.getByName("192.168.10.14");

            System.out.println(inet1);
            //根据域名来获取地址
            InetAddress inet2 = InetAddress.getByName("www.vip.com");
            System.out.println(inet2);
            //获取本机地址
            InetAddress inet3 =  InetAddress.getByName("127.0.0.1");
            System.out.println(inet3);
            //获取本机的IP地址
            InetAddress inet4 = InetAddress.getLocalHost();
            System.out.println(inet4);

            InetAddress inet5    = InetAddress.getLoopbackAddress();
            System.out.println(inet5);


            //getHostName()
            System.out.println(inet2.getHostName());
            //getHostAddress()
            System.out.println(inet2.getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}

使用TCP协议写代码时,需要先执行服务端,在执行客户端,否则会因为找不到指定的端口号而报出异常。

TCPdemo

/**
 * @Auther:Yuhai
 * @Date:2022/4/19-04-19-21:15
 * @Description:IntelliJ IDEA
 * @version:1.0
 */

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;


/**
 *  实现TCP网络编程
 *      例题:
 *          从客户端发送文件到服务端,服务端保存到本地,并返回“发送成功”给客户端
 *          并关闭相应的的链接
 */
public class TCPTest4 {
    /**
     *  这里使用的抛出异常应该用try-catch处理
     * @throws IOException
     */
    @Test
    public void client() throws IOException {
        //造一个socket,这里面写localhost和本机的IP地址都可以
        Socket socket = new Socket(InetAddress.getByName("localhost"),9090);
        //造一个输出流
        OutputStream os = socket.getOutputStream();
        //读取数据的一个流
        FileInputStream fis = new FileInputStream(new File("1.jpeg"));
        //存入缓冲区进行读取
        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[] bytes = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(bytes))!=-1){
            baos.write(bytes,0,len1);
        }
        System.out.println(baos.toString());

        //关闭资源
        baos.close();
        is.close();
        fis.close();
        os.close();
        socket.close();
    }
    @Test
    public void server() throws IOException {
        //造一个socket
        ServerSocket ss = new ServerSocket(9090);
        //获取一个端口号
        Socket socket = ss.accept();
        //获取一个客户端的输入流
        InputStream is = socket.getInputStream();
        //保存数据到本地
        FileOutputStream fos = new FileOutputStream(new File("12.jpeg"));

        byte [] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        System.out.println("图片传输完成");
        //服务端给予客户端反馈
        OutputStream os = socket.getOutputStream();
        os.write("你好,美女,照片已经收到,非常漂亮!".getBytes());
        //关闭资源
        fos.close();
        socket.close();
        is.close();
        ss.close();
        os.close();
    }
}

TCPdemo2

/**
 *  实现TCP的网络编程
 *  例题二:
 *      客户端发送文件给服务端,服务端将文件保存到本地
 */
public class TCPTest3 {
    /**
     *  这里使用的抛出异常应该用try-catch处理
     * @throws IOException
     */
    @Test
    public void client() throws IOException {
        //造一个socket,写入一个指定的端口号
        Socket socket = new Socket(InetAddress.getByName("10.107.10.68"),9090);
        //造一个输出流
        OutputStream os = socket.getOutputStream();
        //读取数据的一个流
        FileInputStream fis = new FileInputStream(new File("1.jpeg"));
        //存入缓冲区进行读取
        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 {
        //造一个socket
        ServerSocket ss = new ServerSocket(9090);
        //获取一个端口号
        Socket socket = ss.accept();
        //获取一个客户端的输入流
        InputStream is = socket.getInputStream();
        //保存数据到本地
        FileOutputStream fos = new FileOutputStream(new File("11.jpeg"));

        byte [] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        //关闭资源
        fos.close();
        is.close();
        socket.close();
    }
}

TCPdemo3

/**
 * L例子一
 */
public class TCPTest2 {
    //客户端
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            //1创建Socket对象,指明服务端的IP和端口号
            InetAddress inet = InetAddress.getByName("10.107.10.68");
            socket = new Socket(inet, 8899);
            //2获取一个输出流,用于输出数据


            os = socket.getOutputStream();
            //3写出数据的一个操作

            os.write("你好,我是大帅哥!".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[1024];
//        int len;
//        while ((len = is.read(buffer))!=-1){
//            String str = new String(buffer,0,len);
//            System.out.println(str);
//        }
            //将字节流整体转换为字符串,这样就可以避免乱码的出现,读取输入流的数据
            baos = new ByteArrayOutputStream();
            //这里面也可以存储的数据变大一些,一般来说1024就可以足够。
            byte[] buffer = new byte[30];
            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 {
            //4关闭资源
            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();
                }
            }
        }
    }
}

在这一章节中,Tcp是重要的,还有一个UDP协议,我们可以稍微了解一下。
在UDP协中,没有执行顺序的先后

public class UDPTest {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();

        String str = "我是UDP请来的java小白!,请大家多多关注!";
        System.out.println("UDP输出的信息:"+str);
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        //构造用于发送长度的分组数组包,具有指定的偏移量,后面是指定的端口号
        DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);

        socket.send(packet);
        socket.close();
    }
    //接收端
    @Test
    public void receiver() throws IOException {
        DatagramSocket soket = new DatagramSocket(9090);
        System.out.println("--------------服务端已开启-----------------");

        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
        soket.receive(packet);

        System.out.println(new String(packet.getData(),0,packet.getLength()));

        soket.close();

    }

}

以上是本章的两个重要的内容,稍后会把本节的练习题整理到博客上。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值