Java学习网络编程

Java学习网络编程

大纲

  1. 网络相关概念
  2. IP地址
  3. 网络协议
  4. InetAdress
  5. Socket

具体案例

1. 网络相关概念

网络

网络通信
Java学习网络编程_第1张图片

2. IP地址

Java学习网络编程_第2张图片

域名

3.网络协议


Java学习网络编程_第3张图片

4. InetAdress

Java学习网络编程_第4张图片
获得本机的名字和IP

 public static void main(String[] args) throws UnknownHostException {
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println(inetAddress);
    }

获取指定主机名字或域名的信息

public static void main(String[] args) throws UnknownHostException {
        InetAddress host1 = InetAddress.getByName("  ");
        InetAddress host2 = InetAddress.getByName("www.baidu.com");
        System.out.println(host1);
        System.out.println(host2);
    }

gethostname 是获取主机名字。或者域名
getHostAddress 是获取IP地址

public static void main(String[] args) throws UnknownHostException {
        InetAddress host1 = InetAddress.getByName("挽天");
        InetAddress host2 = InetAddress.getByName("www.baidu.com");
        String f2 = host2.getHostAddress();
        String f1 = host1.getHostAddress();
        String name = host2.getHostName();
        System.out.println(f1);
        System.out.println(f2);
        System.out.println(name);
    }

5. Socket

Java学习网络编程_第5张图片
Java学习网络编程_第6张图片
Java学习网络编程_第7张图片

TCP编程

在这里插入图片描述
当客户端连接服务端时,服务端是我们固定的端口,而客户端也有一个端口,只不过是TCP/IP协议随机分配的

结束标记
通用:调用socket对象的shutdownOutput()方法
其它:在写入时可以用writeNewLine()来进行结束标记,但这要求读取必须使用readline()方法
注意:写完过后记得使用flush方法刷新
Java学习网络编程_第8张图片
服务端

public class socketServer {
    public static void main(String[] args) throws IOException {
        //服务端
        //在本机的9999端口监听,等待连接
        //前提该端口没有被占用
        //这个serverSocket,可以通过accept()来返回多个socket(高并发,多个客户端来连接服务器端)
        ServerSocket serverSocket = new ServerSocket(9999);
        //当没有客户端连接该端口时。程序会堵塞等待连接
        //  如果在客户端连接,就会返回Socket对象,程序继续执行
        Socket socket = serverSocket.accept();
        //创建一个和这个socket相关的输入流
        InputStream inputStream = socket.getInputStream();
        byte [] buf = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(buf)) != -1){
            //根据读取到的实际长度读取字符串
            System.out.println(new String(buf,0,length));
        }
        //创建一个socket相关的输出流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("hello,client".getBytes());
        outputStream.flush();
        //设置一个结束标记代表传入结束
        socket.shutdownOutput();
        //关闭流
        inputStream.close();
        outputStream.close();
        //关闭这个对象
        socket.close();
        serverSocket.close();
    }
}

客户端

public class socketClient {
    public static void main(String[] args) throws IOException {
        //客户端
        //连接服务器,里面写一个主机地址和端口,这里写的是本机
        //如果联机成功,返回一个socket对象
        Socket socket = new Socket(InetAddress.getLocalHost(),9999);
        //得到一个和socket对象关联的输出流
        OutputStream outputStream = socket.getOutputStream();
        //通过输出流,写入数据到数据通道
        outputStream.write("hello,server".getBytes());
        outputStream.flush();
        //设置一个结束标记
        socket.shutdownOutput();
        //获取和与socket相关联的输入流
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        int length;
        //创建循环读取数据
        while ((length = inputStream.read(bytes)) != -1){
            System.out.println(new String(bytes,0,length));
        }
        //关闭流对象,和socket,避免资源浪费
        inputStream.close();
        outputStream.close();
        socket.close();
    }
}

第二题:
Java学习网络编程_第9张图片
服务端:

public class server1 {
    public static void main(String[] args) throws IOException {
        //创建等待接收
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();
        //创建一个与socket相关的输入流
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        //把接收的数据存入一个byte数组
        byte[] bytes = tool.readArray(bis);
        String fileName = "D:\\java学习\\掉毛.jpg";
        //创建一个输出流
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
        //把得到的数据写入磁盘
        bos.write(bytes);
        bos.close();
        //创建一个与socket相关的输出流
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        //传递信息
        writer.write("收到图片");
        writer.flush();
        socket.shutdownOutput();
        //关闭流
        bis.close();
        writer.close();
        socket.close();
        serverSocket.close();
    }
}

客户端:

public class client1 {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        String fileName = "D:\\java学习\\图片\\蛋糕.jpg";
        //创建一个输入流。从磁盘读取信息
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
        //把读取到的信息存入一个字节数组
        byte [] bytes = tool.readArray(bis);
        //创建一个与socket相关的输出流
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
        //传出数据
        bos.write(bytes);
        socket.shutdownOutput();
        //创建一个与socket相关的输入流
        InputStream inputStream = socket.getInputStream();
        //读取信息,并返回一个字符串
        String s = tool.readString(inputStream);
        //输出信息
        System.out.println(s);
        //关闭资源
        inputStream.close();
        socket.close();
        bos.close();
        bis.close();
    }
}

工具类:

public class  tool {
    public static byte [] readArray(InputStream is) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = is.read(bytes)) != -1){
            bos.write(bytes,0,len);
        }
        byte [] array = bos.toByteArray();
        bos.close();
        return array;
    }
    public static String readString (InputStream is) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null){
            stringBuilder.append(line + "\r\n");
        }
        return stringBuilder.toString();
    }
}

netstat指令

Java学习网络编程_第10张图片

UDP编程


Java学习网络编程_第11张图片
Java学习网络编程_第12张图片
接收端/发送端:

public class UDPReceive {
    public static void main(String[] args) throws IOException {
        //创建一个 DatagramSocket对象
        DatagramSocket datagramSocket = new DatagramSocket(9999);
        //构建一个DatagramPacket,传入bytes数组
        byte[] bytes = new byte[64 * 1024];
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
        //调用接收方法接收数据
        //把接收到的数据,填充到DatagramPacket里面去
        //这个receive方法,没有接收到数据,程序就会阻塞
        datagramSocket.receive(packet);
        //进行拆包,并显示内容
        int length = packet.getLength();//得到长度
        byte [] data = packet.getData();//得到数组
        String s = new String (data,0,length);
        System.out.println(s);
        //发送内容
        byte[] bytes1 = "好的,明天见".getBytes();
        packet = new DatagramPacket(bytes1, bytes1.length, InetAddress.getByName("192.168.101.8"), 8888);
        datagramSocket.send(packet);
        //关闭流
        datagramSocket.close();
    }
}

发送端/接收端:

public class UDPSend {
    public static void main(String[] args) throws IOException {
        //创建一个DatagramSocket准备在8888端口发送,接收数据
        DatagramSocket datagramSocket = new DatagramSocket(8888);
        //将需要发送的数据封装到DatagramPacket
        //传入byte数组,数组长度,目标地址和端口
        byte[] bytes = "hello,明天吃火锅".getBytes();
        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("192.168.101.8"), 9999);
        //发出数据
        datagramSocket.send(packet);
        //接收数据
        byte[] bytes1 = new byte[1024 * 64];
        packet = new DatagramPacket(bytes1, bytes1.length);
        datagramSocket.receive(packet);
        byte[] data = packet.getData();
        int length = packet.getLength();
        String s = new String(data,0,length);
        System.out.println(s);
        //关闭流
        datagramSocket.close();

    }
}

你可能感兴趣的:(大一学java,java基本语法,java,学习,网络)