Java狂神说网络编程笔记

Java狂神说网络编程笔记_第1张图片
Java狂神说网络编程笔记_第2张图片
Java狂神说网络编程笔记_第3张图片

  • IP
    Java狂神说网络编程笔记_第4张图片
import java.net.InetAddress;
import java.net.UnknownHostException;


public class Hello {
     //

// 测试IP
    public static void main(String[] args)  {
     
        try {
     
            //返回主机
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress);
            InetAddress inetAddress2 = InetAddress.getByName("localhost");
            System.out.println(inetAddress);
            InetAddress inetAddress3 = InetAddress.getLocalHost();
            System.out.println(inetAddress);

            //返回网站地址
            InetAddress inetAddress1 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress1);

            //常用方法
            //System.out.println(inetAddress1.getAddress());
            System.out.println(inetAddress1.getCanonicalHostName()); //规范名,
            System.out.println(inetAddress1.getHostAddress());//ip
            System.out.println(inetAddress2.getHostName());//域名
        } catch (UnknownHostException e) {
     
            e.printStackTrace();
        }
    }
}

Java狂神说网络编程笔记_第5张图片

  • 一些命令
    Java狂神说网络编程笔记_第6张图片

import java.net.InetSocketAddress;


public class Hello {
     //


    public static void main(String[] args)  {
     
      InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1",8080);
      InetSocketAddress inetSocketAddress1 = new InetSocketAddress("localhost",8080);
        System.out.println(inetSocketAddress);
        System.out.println(inetSocketAddress1);

        System.out.println(inetSocketAddress.getAddress()); //返回IP
        System.out.println(inetSocketAddress.getHostName()); //返回名字
        System.out.println(inetSocketAddress.getPort());  //返回端口
    }
}
  • 通信协议
    Java狂神说网络编程笔记_第7张图片
    Java狂神说网络编程笔记_第8张图片
    Java狂神说网络编程笔记_第9张图片
package kssManyThread;


import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


//客户端
public class day1 {
     

    public static void main(String[] args) throws IOException {
     
        //1.要知道服务器的地址
        InetAddress ServerIp = InetAddress.getByName("127.0.0.1");

        //2.端口号
        int port = 9999;

        //3.创建一个socket连接
        Socket socket = new Socket(ServerIp, port);

        //4.发送消息 IO流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("你好,欢迎狂神说Java".getBytes(StandardCharsets.UTF_8));

        if(outputStream!=null){
     
            outputStream.close();
        }
        if (socket!=null){
     
            socket.close();
        }


    }
}
package kssManyThread;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务端
public class day2 {
     

    public static void main(String[] args) throws IOException {
     
       //1.我得有一个地址
        ServerSocket serverSocket = new ServerSocket(9999);

        //2.等待客户端连接过来
        Socket socket = serverSocket.accept();

        //3.读取客户端的消息
        InputStream is = socket.getInputStream();

        //管道流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
     
            baos.write(buffer,0,len);
        }
        System.out.println(baos.toString());
        if (baos!=null){
     
            baos.close();
        }
        if (is!=null){
     
            is.close();
        }
        if (socket!=null) {
     
            socket.close();
        }
        if (serverSocket!=null) {
     
            serverSocket.close();
        }
    }
}

  • 发送图片(文件)
package kssManyThread;


import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


//客户端
public class day1 {
     

    public static void main(String[] args) throws IOException {
     
        //1.要知道服务器的地址
        InetAddress ServerIp = InetAddress.getByName("127.0.0.1");

        //2.端口号
        int port = 9999;

        //3.创建一个socket连接
        Socket socket = new Socket(ServerIp, port);

        //4.发送消息 IO流
        OutputStream outputStream = socket.getOutputStream();

        //读取文件
        FileInputStream fis = new FileInputStream(new File("E:\\idea\\WorkerSystem\\src\\Worker\\t01369c7b27429f28cb.jpg"));
        byte[] buffer = new byte[1024];
        int len;
        while((len=fis.read())!=-1){
     
            outputStream.write(buffer,0,len);
        }


        //通知服务器,我已经结束了
        socket.shutdownOutput();
        
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte [] buffer2 = new byte[2014];
        int len2;
        while((len2=inputStream.read(buffer2))!=-1){
     
            baos.write(buffer2,0,len2);
        }
        System.out.println(baos.toString());
        if(outputStream!=null){
     
            outputStream.close();
        }
        if (socket!=null){
     
            socket.close();
        }
    }
}
package kssManyThread;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

//服务端
public class day2 {
     

    public static void main(String[] args) throws IOException {
     
       //1.我得有一个地址
        ServerSocket serverSocket = new ServerSocket(9999);

        //2.等待客户端连接过来
        Socket socket = serverSocket.accept();

        //3.读取客户端的消息
        InputStream is = socket.getInputStream();

       //文件输出
        FileOutputStream fos = new FileOutputStream(new File("re.jpg"));
        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(StandardCharsets.UTF_8));
        if (fos!=null){
     
            fos.close();
        }
        if (is!=null){
     
            is.close();
        }
        if (socket!=null) {
     
            socket.close();
        }
        if (serverSocket!=null) {
     
            serverSocket.close();
        }
    }
}

  • UDP案例
kage kssManyThread;


import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;

//UDP不需要连接服务器
public class day1 {
     

    public static void main(String[] args) throws IOException {
     


        //1.建立一个socket
        DatagramSocket socket = new DatagramSocket();

        //2.建立包
        String message = "你好啊,服务器";
        //发送给谁
        InetAddress localhost = InetAddress.getByName("localhost");
        int port = 9090;
        DatagramPacket packet = new DatagramPacket(message.getBytes(StandardCharsets.UTF_8), 0, message.getBytes(StandardCharsets.UTF_8).length,localhost,port );

        //3.发送包
        socket.send(packet);

        //4.关闭流
        socket.close();
    }
}
package kssManyThread;


import java.net.DatagramPacket;
import java.net.DatagramSocket;


public class day2 {
     

    public static void main(String[] args) throws Exception {
     
        //开放端口
        DatagramSocket socket = new DatagramSocket(9090);

        //接受数据包
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);//接受

        socket.receive(packet);

        System.out.println(new String(packet.getData()));
        //关闭链接
        socket.close();
    }
}
  • 模拟两个人在聊天
package kssManyThread;


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

//接受的线程
public class day2 implements Runnable{
     
    DatagramSocket socket = null;
    private int port;
    private String msgFrom;
    public day2(int port,String msgFrom) throws SocketException {
     
        this.port = port;
        this.msgFrom = msgFrom;
        socket = new DatagramSocket(port);
    }

    @Override
    public void run() {
     
        while (true) {
     

            try {
     
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);
                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(msgFrom+":"+receiveData);
                if (receiveData.equals("bye")) {
     
                    break;
                }
            } catch (IOException e) {
     
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

package kssManyThread;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;

//发送的线程
public class day1 implements Runnable {
     
    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIP;
    private int toPort;

    public day1(int fromPort, String toIP, int toPort) throws SocketException {
     
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        socket = new DatagramSocket(fromPort);
        reader = new BufferedReader(new InputStreamReader(System.in));
    }


    @Override
    public void run() {
     
        while (true){
     
            try {
     
                String data = reader.readLine();
                byte[] datas = data.getBytes(StandardCharsets.UTF_8);
                DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
                socket.send(packet);
                if(data.equals("bye")){
     
                    break;
                }
            } catch (IOException e) {
     
                e.printStackTrace();
            }

        }
        socket.close();
    }

}
package kssManyThread;

import java.net.SocketException;

public class Talk {
     
    public static void main(String[] args) throws SocketException {
     
        //开启两个线程
        new Thread(new day1(7777,"localhost",9999)).start();
        new Thread(new day2(8888,"老师")).start();
    }
}

package kssManyThread;

import java.net.SocketException;

public class Talk2 {
     
    public static void main(String[] args) throws SocketException {
     
        //开启两个线程
        new Thread(new day1(5555,"localhost",8888)).start();
        new Thread(new day2(9999,"学生")).start();
    }
}

  • 下载网络资源(试了个图片,不能干坏事对吧?)
package kssManyThread;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class last {
     
    public static void main(String[] args) throws IOException {
     
        //1.下载地址
        URL url = new URL("");//自己去想

        //2.连接到这个资源HTTP
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fos = new FileOutputStream("图标.png");//看你下载什么文件

        byte[] buffer = new byte[1024];
        int len;
        while((len=inputStream.read(buffer))!=-1){
     
            fos.write(buffer,0,len);
        }
        fos.close();
        inputStream.close();
        urlConnection.disconnect();
    }
}

你可能感兴趣的:(Java网络编程,socket,网络,java)