JAVA网络编程

JAVA网络编程

InetAddress 类 (IP类)

public class TestInetAddress {
    public static void main(String[] args) {
        try {
            //查询本机地址
            InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
            System.out.println(inetAddress1);
            InetAddress inetAddress3 = InetAddress.getByName("localhost");
            System.out.println(inetAddress3);
            InetAddress inetAddress4 = InetAddress.getLocalHost();
            System.out.println(inetAddress4);

            //查询网站ip地址
            InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com");
            System.out.println(inetAddress2);

            //常用方法
            //System.out.println(inetAddress2.getAddress());
            //System.out.println(inetAddress2.getCanonicalHostName());
            System.out.println(inetAddress2.getHostAddress()); //ip
            System.out.println(inetAddress2.getHostName()) ; //域名或者自己电脑的名字


        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

    }
}

端口

cmd命令

netstat -ano  #查看所有端口
netstat -ano|findstr "5900"  # 查看指定的端口
tasklist | findstr "5900" # 查看进程 + 端口 + 内存等

InetSocketAddress类

public class TestInetSocketAddress {
    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());
        System.out.println(inetSocketAddress.getHostName()); //地址
        System.out.println(inetSocketAddress.getPort());  //端口
    }
}

TCP实现聊天(传输控制协议)

服务器端

  1. 根据服务端口建立服务套接字 ServerSocket
  2. 等待用户的连接 Socket
  3. 接受用户的消息
public class TcpServerDemo01 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        //1.需要一个地址
        try {
            //新建一个服务器端套接字(通过端口号)
            serverSocket = new ServerSocket(9999);
            //2.等待客户端连接
            socket = serverSocket.accept();
            //3.读取客户端消息
            inputStream = socket.getInputStream();
            //管道流
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len=inputStream.read(buffer))!=-1)
            {
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(baos!=null)
            {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream!=null)
            {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null)
            {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null)
            {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

客户端

  1. 根据客户端的IP地址和端口号连接服务器Socket
  2. 发送消息
public class TcpClientDemo01 {
    public static void main(String[] args) {
        //1.要知道服务器的地址
        try {
            InetAddress serverIP = InetAddress.getByName("127.0.0.1");
            int port = 9999;
            //2.通过服务器IP地址、应用程序端口号,创建一个socket连接
            Socket socket = new Socket(serverIP,port);
            //3.发送消息 IO流
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("你好,我是陆源东".getBytes());

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

TCP实现文件上传

服务器端

public class TcpServerDemo02 {
    public static void main(String[] args) {
        //1.创建服务
        try {
            ServerSocket serverSocket = new ServerSocket(9000);
            //2.监听客户端的连接
            Socket socket = serverSocket.accept();
            //3.获取输入流
            InputStream inputStream = socket.getInputStream();
            //4.文件输出
            FileOutputStream fos = new FileOutputStream(new File("receive.png"));
            byte[] buffer = new byte[1024];
            int len;
            while((len=inputStream.read(buffer))!=-1)
            {
                fos.write(buffer,0,len); //长度
            }
            //通知客户端接收完毕
            socket.getOutputStream().write("我接收完毕了,可以断开连接".getBytes());

            //5.关闭资源
            fos.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

客户端

public class TcpClientDemo02 {
    public static void main(String[] args) {
        //1.创建一个Socket连接
        try {
            Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
            //2.创建一个输出流
            OutputStream os = socket.getOutputStream();
            //3.读取文件
            FileInputStream fis = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\mail-Java\\src\\img.png"));
            //4.写出文件
            byte[] buffer = new byte[1024];
            int len;
            while((len=fis.read(buffer))!=-1)
            {
                os.write(buffer,0,len); //长度
            }
            //通知服务器: 我已经传输完了
            socket.shutdownOutput();
            //确定服务器接收完毕,才能够断开连接
            InputStream inputStream = socket.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes2 = new byte[2048];
            int len2 ;
            while((len=inputStream.read(buffer))!=-1)
            {
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
            //5.关闭资源
            baos.close();
            inputStream.close();
            fis.close();
            os.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

UDP消息发送(用户数据报协议)

UDP数据传输不需要区分客户端与服务器端,只针对用户数据包进行传输。

发送端

//在发送端,发送的目的地放在数据包里面,不在socket
public class UdpSendDemo01{
    public static void main(String[] args)
    {
        try{
       		//1.建立一个UDP的DatagramSocket
        	DatagramSocket socket = new DatagramSocket();
        	//2.建立一个用户数据包 DatagramPacket
        	//发送什么内容?
       	 	String msg = "你好啊。服务器";
        	//发给谁? 通过InetAddress(IP地址)和port端口号来确定
        	InetAddress loaclhost = InetAddress.getByName("127.0.0.1");
        	int port = 9000;
        	DatagramPacket datagramPacket = 
        	new DatagramPacket(msg.getBytes(),0,msg.getBytes().length.localhost,port);
        	//3.建立好了数据包之后,就发送出去
       	 	socket.send(datagramPacket);
        	//4.关闭流
        	socket.close();     
        }catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}

接收方

//在接收端,socket
public class UdpReceiveDemo01{
    public static void main(String[] args)
    {
        try{
            //1.建立一个DatagramSocket
            DatagramSocket socket = new DatagramSocket(9000);
            //2.接收数据包(通过DatagramPacket)
            byte[] buffer = new byte[2048]; 
            DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
            //接收数据
            socket.receive(packet); //数据会直接被写入packet中
            //输出数据内容
            System.out.println(new String(packet.getData(),0,packet.getLength()));
            //3.关闭流
            socket.close;
        }catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

UDP实现聊天(单向)

发送方

public class UdpSendDemo02 {
    public static void main(String[] args) {
        try {
            //相互传输数据,因此都需要知道
            DatagramSocket socket = new DatagramSocket(8888);
            //准备数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            while(true)
            {
                String data = reader.readLine();
                DatagramPacket packet = new DatagramPacket(data.getBytes(),0,data.length(),InetAddress.getByName("127.0.0.1"),6666);
                socket.send(packet);
                if(data.equals("bye"))
                {
                    break;
                }
            }
            reader.close();
            socket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

接收方

public class UdpReceiveDemo02 {
    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket(6666);
            /*BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String data = reader.readLine();
            DatagramPacket packet = new DatagramPacket(data.getBytes(),0,data.length(), InetAddress.getByName("127.0.0.1"),8888);*/
            //准备接收包
            byte[] container = new byte[2048];
            while(true)
            {
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                socket.receive(packet);
                //断开连接 , 接收到bye
                byte[] data= packet.getData();
                String receiveData = new String(data,0,data.length);
                System.out.println(receiveData);
                if(receiveData.equals("bye"))
                {
                    break;
                }
            }
            socket.close();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用多线程进行双向通信

UDP消息发送工具类

public class TalkSend implements Runnable{
    DatagramSocket socket = null;
    BufferedReader reader = null;
    private int fromPort; //本地端口号
    private String toIP; //接收端ip地址
    private int toPort;  //接收端端口号

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;
        try {
            this.socket = new DatagramSocket(fromPort);
            this.reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @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();
    }
}

UDP消息接收工具类

public class TalkReceive implements Runnable{
    DatagramSocket socket = null;
    private String msgFrom;
    private int port;

    public TalkReceive(int port,String msgFrom)
    {
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        this.port = port;
        this.msgFrom = msgFrom;
    }
    @Override
    public void run() {
        while(true)
        {
            try {
                //准备接收数据包
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container,0,container.length);
                socket.receive(packet);
                //断开连接 bye
                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();
    }
}

通信方1和2

public class TalkStudent {
    public static void main(String[] args) {
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"老师")).start();
    }
}
public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"学生")).start();
    }
}

URL下载网络资源

URL(统一资源定位符) : 定位资源的,定位互联网上的某个资源

组成结构 :

协议://ip地址:端口/项目名/资源

http://localhost:8080/helloworle/index.jsp

可以使用URL类来对URL进行操作

public class URLDemo01 {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/hellworld/index.jsp");
            System.out.println(url.getProtocol()); //协议
            System.out.println(url.getHost()); //主机ip
            System.out.println(url.getPort()); //端口号
            System.out.println(url.getPath()); //文件地址
            System.out.println(url.getFile());//文件全路径
            System.out.println(url.getQuery());//文件全路径
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

使用URL下载网络资源(qq音乐网页扒歌)

public class UrlDown {
    public static void main(String[] args) {
        //1.下载地址
        try {
            URL url = new URL("http://dl.stream.qqmusic.qq.com/C40000136uPz3RgR3W.m4a?guid=4026009763&vkey=83524C23D2361AC30986B9E56E5B713E020210F354178FEC19EE0416BF29CC042579B9CB4A257028F4184CFBFA50FD2F4C38BDD1014A20B2&uin=&fromtag=66");
            //2.连接到这个资源HTTP url.openConnection 打开HTTP连接 HttpURLConnection
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fos = new FileOutputStream("2.mp3");
            byte[] buffer = new byte[1024];
            int len ;
            while((len=inputStream.read(buffer))!=-1)
            {
                fos.write(buffer,0,len);
            }
            fos.close();
            inputStream.close();
            urlConnection.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值