java网络编程

java中利用 InetAddress 类来代表ip地址

本地回路地址:127.0.0.1 对应着:localhost

实例化InetAddress: getByName(String host) getLocalHost()
常用方法: //getHostName() getHostAddress()

public String getHostAddress():返回 IP 地址字符串(以文本表现形式)。

public String getHostName():获取此 IP 地址的主机名

public boolean isReachable(int timeout):测试是否可以达到该地址

package com.atguigu.java;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author ycy
 * @create 2020 - 07 -14 -8:59 下午
 */
public class InetAddressTest {
    public static void main(String[] args) {
        try {
            InetAddress inet1 = InetAddress.getByName("192.168.10.14");//代表一个IP地址
            System.out.println(inet1);///192.168.10.14

            InetAddress inet2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inet2);//www.baidu.com/220.181.38.150

            InetAddress inet3 = InetAddress.getByName("localhost");
            System.out.println(inet3);//localhost/127.0.0.1

            //获取本机ip
            InetAddress inet4 = InetAddress.getLocalHost();
            System.out.println(inet4);//MacBook-Pro.local/127.0.0.1

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

端口号:
在这里插入图片描述

TCP

package com.atguigu.java;

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;

/**
 * @author ycy
 * @create 2020 - 07 -14 -9:42 下午
 */
public class TCPTest1 {
    //客户端发信息给服务器端
    @Test
    public void client() {
        Socket socket = null;
        OutputStream os = null;
        try {
            
            //1.创建Socket对象,指明服务器端的ip和端口号
            InetAddress inet1 = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet1, 8889);
            //2。获取一个输出流,用于输出数据
            os = socket.getOutputStream();
            //3。写出数据
            os.write("你好".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //4。关闭资源
                if (os != null)
                    os.close();
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //服务器端将信息显示在控制台上
    @Test
    public void server() throws IOException {
        
        //1。创建服务器端server socket ,指明自己端口号
        ServerSocket serverSocket = new ServerSocket(8889);

        //2。调用accept()方法,接受来自客户端的socket
        Socket socket = serverSocket.accept();

        System.out.println("收到了来自"+socket.getInetAddress().getHostAddress()+"的数据");//收到了来自127.0.0.1的数据

        //3。获取输入流
        InputStream inputStream = socket.getInputStream();

//        不建议这样写,可能乱码
//        int len;
//        byte[] bytes = new byte[20];
//        while ((len = inputStream.read(bytes)) != -1){
//            String str = new String(bytes, 0, len);
//            System.out.println(bytes);
//        }


        //4。读取输入流数据
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[5];

        int len;

        while ((len = inputStream.read(bytes)) != -1) {
            baos.write(bytes, 0, len);
        }
        System.out.println(baos.toString());//你好
        //5。关闭资源
        inputStream.close();
        socket.close();
        baos.close();
        serverSocket.close();
    }
}

package com.atguigu.java;

import org.junit.Test;

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

/**
 * 从客户端发送文件给服务端,
 * 服务端保存到本地。并返回“发送成功”给 客户端。并关闭相应的连接。
 *
 * @author ycy
 * @create 2020 - 07 -15 -9:16 上午
 */
public class TCPTest2 {
    @Test
    public void client() {
        Socket socket = null;
        OutputStream ops = null;
        FileInputStream fis = null;
        InputStream inputStream = null;
        try {
            socket = new Socket(InetAddress.getByName("localhost"), 9090);

            ops = socket.getOutputStream();

            fis = new FileInputStream("dang-an.jpg");
            int len;
            byte[] bytes = new byte[1024];

            while ((len = fis.read(bytes)) != -1) {
                ops.write(bytes, 0, len);
            }
            //关闭数据输出
            socket.shutdownOutput();
            //接受来自服务器的信息
            inputStream = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((len = inputStream.read(bytes))!=-1){
                baos.write(bytes,0,len);
            }
            System.out.println(baos);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (ops != null)
                    ops.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void server() {

        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is = null;
        FileOutputStream fos = null;
        OutputStream os = null;
        try {
            serverSocket = new ServerSocket(9090);

            socket = serverSocket.accept();

            is = socket.getInputStream();

            fos = new FileOutputStream("dang_dang1.jpg");

            int len;
            byte[] bytes = new byte[1024];
            while ((len = is.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
            //向客户端反馈
            os = socket.getOutputStream();
            os.write("你好,文件已收到".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();

                if (is != null) {
                    is.close();
                }
                if (socket != null)
                    socket.close();
                if (serverSocket != null)
                    serverSocket.close();
                if (os != null){
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

UDP

类 DatagramSocket 和 DatagramPacket 实现了基于 UDP 协议网络程序。
UDP数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证 UDP数据报一定能够安全送到目的地,也不能确定什么时候可以抵达。
DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP 地址和端口号以及接收端的IP地址和端口号。
UDP协议中每个数据报都给出了完整的地址信息,因此无须建立发送方和 接收方的连接。如同发快递包裹一样。

package com.atguigu.java;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author ycy
 * @create 2020 - 07 -15 -10:18 上午
 */
public class UDPTest {

    //发送端
    @Test
    public void sender() {
        DatagramSocket socket = null;//这里不带参数,虽然有别的构造器,但一般目的地不放在socket里
        try {
            socket = new DatagramSocket();

            byte[] bytes = new String("我是导弹").getBytes();
            DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getLocalHost(), 9080);

            socket.send(packet);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null)
                socket.close();
        }

    }

    //接受端
    @Test
    public void receiver() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(9080);//这里要指明自己的端口号

            byte[] buffer = new byte[100];

            DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);//接受端不用再指明端口号

            socket.receive(packet);

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

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }
}

URL

URL的基本结构由5部分组成: <传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
例如: http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
#片段名:即锚点,例如看小说,直接定位到章节
参数列表格式:参数名=参数值&参数名=参数值…

方法
public String getProtocol( ) 获取该URL的协议名
public String getHost( ) 获取该URL的主机名
public String getPort( ) 获取该URL的端口号
public String getPath( ) 获取该URL的文件路径
/helloworld/index.jsp
public String getFile( ) 获取该URL的文件名
/helloworld/index.jsp#a?username=shkstar
public String getQuery() 获取该URL的查询名username=shkstart

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值