JavaSE-网络编程

package com.btp.t4.net;

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

/*
 * 网络通信的第一个要素:IP地址。通过IP地址,唯一的定位互联网上一台主机
 * InetAddress:位于java.net包下
 * 1.InetAddress用来代表IP地址。一个InetAddress对象就代表着一个IP地址
 * 2.如何创建InetAddress的对象:getByName(String host)
 * 3.getHostName():获取IP地址对应的域名
 *   getHostAddress():获取IP地址
 */
public class TestInetAddress {
    public static void main(String[] args) throws UnknownHostException{
        //创建一个InetAddress对象
        InetAddress inet=InetAddress.getByName("www.baidu.com");
        System.out.println(inet);
        
        System.out.println(inet.getHostName());
        System.out.println(inet.getHostAddress());
        
        inet=InetAddress.getByName("111.13.100.92");
        System.out.println(inet.getHostName());
        System.out.println(inet.getHostAddress());
        
        //本机的IP
        InetAddress inet1=InetAddress.getLocalHost();
        System.out.println(inet1);
        
        System.out.println(inet1.getHostName());
        System.out.println(inet1.getHostAddress());
    }
}
TestInetAddress
package com.btp.t4.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.Test;

//TCP编程例一:客户端给服务端发送信息。服务端输出此信息到控制台上
//网络编程实际上就是Socket的编程,IP地址和端口号组成一个套接字Socket
public class TestTCP1 {
    //客户端
    @Test
    public void client(){
        
        Socket socket = null;
        OutputStream os = null;
        try {
            //1.创建一个Socket的对象,通过构造器指明服务端的IP地址,以及其接收程序的端口号
                socket = new Socket(InetAddress.getByName("192.168.0.104"),9091);
            //2.getOutputStream():发送数据,方法返回OutputStream的对象
                os = socket.getOutputStream();
            //3/具体的输出过程
                os.write("我是客户端。".getBytes());
        } catch (UnknownHostException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO 自动生成的 catch 块
            e1.printStackTrace();
        }finally{
            //4.关闭相应的流和Socket对象
            if(os!=null){
            try {
                os.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            }
            if(socket!=null){
            try {
                socket.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            }
        }
        
        
        
        
    }
    
    //服务端
    @Test
    public void server(){
                ServerSocket ss = null;
                Socket s = null;
                InputStream is = null;
                try {
                    //1.创建一个ServerSocket的对象,通过构造器指明自身的端口号
                    ss = new ServerSocket(9091);
                    //2.调用其accept()方法,返回一个Socket的对象
                    s = ss.accept();
                    //3.调用Socket对象的getInputStream()获取一个从客户端发送过来的输入流
                    is = s.getInputStream();
                    //4.对获取的输入流进行的操作
                    byte[] b=new byte[20];
                    int len;
                        while((len=is.read(b))!=-1){
                            String str=new String(b,0,len);
                            System.out.println(str);
                        }
                        System.out.println("收到来自于"+s.getInetAddress().getHostAddress()+"的连接");
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }finally{
                //5.关闭相应的Socket和流和ServerSocket
                    if(s!=null){
                    try {
                        s.close();
                    } catch (IOException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }
                    }if(is!=null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }
                    }if(ss!=null){
                    try {
                        ss.close();
                    } catch (IOException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }
                    }
                }
            
        
    }
}
TestTCP1
package com.btp.t4.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.Test;

//TCP编程例二:客户端给服务端发送信息,服务端将信息打印到控制台上,同时发送“已收到信息”给客户端
public class TestTCP2 {
    //客户端
    @Test
    public void client(){
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;
        try {
            socket = new Socket(InetAddress.getByName("192.168.1.101"),8990);
            os = socket.getOutputStream();
            os.write("我是客户端".getBytes());
            //发完要告诉服务端:shutdownOutput():执行此方法,显式的告诉服务端发送完毕
            socket.shutdownOutput();
            
            is = socket.getInputStream();
            byte[] b=new byte[20];
            int len;
            while((len=is.read(b))!=-1){
                String str=new String(b,0,len);
                System.out.println(str);
            }
        } catch (UnknownHostException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        finally{
            if(is!=null){
        try {
            is.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        }if(os!=null){
        try {
            os.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        }if(socket!=null){
        try {
            socket.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        }
        }
    }
    
    
    
    //服务端
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket s = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            ss = new ServerSocket(8990);
            s = ss.accept();
            is = s.getInputStream();
            byte[] b=new byte[20];
            int len;
            while((len=is.read(b))!=-1){
                String str=new String(b,0,len);
                System.out.println(str);
            }
            
            os = s.getOutputStream();
            os.write("我已收到你的信息".getBytes());
            s.shutdownInput();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        finally{
        if(os!=null){
        try {
            os.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        }if(is!=null){
        try {
            is.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        }if(s!=null){
        try {
            s.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        }if(ss!=null){
        try {
            ss.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        }
        }
    }
}
TestTCP2
package com.btp.t4.net;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.junit.Test;

//TCP编程例三:从客户端发送文件给服务端,服务端保存到本地,并返回“发送成功”给客户端,并关闭相应的连接
//以下程序要使用try-catch语句,本例图方便只抛出异常
public class TestTCP3 {
    @Test
    public void client() throws Exception{
        //1.创建Socket的对象
        Socket socket =new Socket(InetAddress.getByName("192.168.1.101"),8989);
        //2.从本地获取一个文件发送给服务端
        OutputStream os=socket.getOutputStream();
        FileInputStream fis=new FileInputStream(new File("hello1.txt"));
        byte[] b=new byte[20];
        int len;
        while((len=fis.read(b))!=-1){
            os.write(b,0,len);
        }
        socket.shutdownOutput();
        //3.接收来自于服务端的信息
        InputStream is=socket.getInputStream();
        byte[] b1=new byte[20];
        int len1;
        while((len1=is.read(b1))!=-1){
            String str=new String(b1,0,len1);
            System.out.println(str);
        }
        //4.关闭相应的流和Socket对象
        is.close();
        os.close();
        fis.close();
        socket.close();
    }
    
    @Test
    public void server() throws Exception{
        //1.创建一个ServerSocket的对象
        ServerSocket ss=new ServerSocket(8989);
        //2.调用其accept()方法,返回一个Socket的对象
        Socket s=ss.accept();
        //3.将从客户端发送的文件保存到本地
        InputStream is=s.getInputStream();
        FileOutputStream fos=new FileOutputStream(new File("Naruto.txt"));
        byte[] b=new byte[20];
        int len;
        while((len=is.read(b))!=-1){
            fos.write(b, 0, len);
        }
        System.out.println("收到来自于"+s.getInetAddress().getHostAddress()+"的文件");
        //4.发送“接收成功”的信息反馈给客户端
        OutputStream os=s.getOutputStream();
        os.write("文件发送成功!".getBytes());
        //5.关闭相应的流和Socket对象,ServerSocket对象
        os.close();
        fos.close();
        is.close();
        s.close();
        ss.close();
    }
}
TestTCP3
package com.btp.t4.net;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.junit.Test;

//客户端给服务端发送文本,服务端会将文本转成大写再返回给客户端
public class TestTcp {
    @Test
    public void client(){
        Socket socket = null;
        OutputStream os = null;
        FileInputStream fis = null;
        InputStream is=null;
        try {
            //1.
            socket = new Socket(InetAddress.getByName("192.168.1.100"),9090);
            //2.
            os = socket.getOutputStream();
            //3.向服务端发送数据
            fis = new FileInputStream(new File("data.txt"));
            byte[] b=new byte[1];
            int len;
            while((len=fis.read(b))!=-1){
                os.write(b,0,b.length);
            }
            socket.shutdownOutput();
            //4.接收来自于服务端的数据
            is=socket.getInputStream();
            byte[] b1=new byte[1];
            int len1;
            while((len1=is.read(b1))!=-1){
                String str=new String(b1,0,b1.length);
                System.out.print(str);
            }
            
        } catch (UnknownHostException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        finally{
            if(is!=null)
            {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
            if(os!=null){
           try {
            os.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
            }if(fis!=null){
        try {
            fis.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
            }if(socket!=null){
        try {
            socket.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
            }
        }
    }
    
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket s = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            //1/
            ss = new ServerSocket(9090);
            //2.
            s = ss.accept();
            //3.
            is = s.getInputStream();
            os = s.getOutputStream();
            //4.把来自客户端的文本转换为大写并发送给客户端
            byte[] b=new byte[1];
            int len;
            while((len=is.read(b))!=-1){
                for(int i=0;i<b.length;i++)
                {
                    b[i]=(byte) (b[i]-32);
                }
                os.write(b,0,b.length);
            }
            s.shutdownOutput();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        finally{
            if(os!=null){
        try {
            os.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
            }if(is!=null){
        try {
            is.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
            }if(s!=null){
        try {
            s.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
            }if(ss!=null){
        try {
            ss.close();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
            }
        }
    }
}
TestTcp
package com.btp.t4.net;

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

import org.junit.Test;
//UDP编程的实现:把DatagramSocket对象看成是接收器发射器,DatagramPacket对象是数据报,传输单元
public class TestUDP {
    //发送端
    @Test
    public void send(){
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket();
            byte[] b="我是要发送的数据".getBytes();
            //创建一个数据报,每一个数据报都不能大于64k,都记录着数据信息,发送端的IP,端口号,以及
            //要发送到的接收端的IP,端口号
            DatagramPacket pack=new DatagramPacket(b, 0, b.length,
                    InetAddress.getByName("192.168.1.100"), 9090);
            
            ds.send(pack);
        } catch (SocketException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (UnknownHostException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }finally{
            if(ds!=null){
             ds.close();
            }
        }
        
    }
    
    //接收端
    @Test
    public void receive(){
        DatagramSocket ds = null;
        try {
            ds = new DatagramSocket(9090);
            byte[] b=new byte[1024];
            DatagramPacket pack=new DatagramPacket(b, 0, b.length);
            ds.receive(pack);
            String str=new String(pack.getData(),0,pack.getLength());
            System.out.println(str);
        } catch (SocketException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        finally{
            if(ds!=null)
               ds.close();
        }
    }
}
TestUDP
package com.btp.t4.net;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

//URL:统一资源定位符,一个URL对象对应着互联网上的一个资源。
//我们可以通过URL的对象调用其相应的方法将此资源读取(下载)
public class TestURL {
    public static void main(String[] args) throws IOException
    {
        //1.创建一个URL对象
        URL url=new URL("http://pica.nipic.com/2007-11-09/200711912453162_2.jpg");//File file=new File("文件路径");
        System.out.println(url.getProtocol());//获取该URL的协议名
        System.out.println(url.getHost());//获取该URL的主机名
        System.out.println(url.getPort());//获取该URL的端口号
        System.out.println(url.getPath());//获取该URL的文件路径
        System.out.println(url.getFile());//获取该URL的文件名
        System.out.println(url.getRef());//获取该URL在文件中的相对位置
        System.out.println(url.getQuery());//获取该URL的查询名
        //如何将服务端的资源读取进来:openStream()
        InputStream is=url.openStream();
        byte[] b=new byte[20];
        int len;
        while((len=is.read(b))!=-1){
            String str=new String(b,0,len);
            System.out.println(str);
        }
        is.close();
        
        //如果既有数据的输入又有数据的输出,则考虑使用URLConnection
        URLConnection urlConn=url.openConnection();
        InputStream is1=urlConn.getInputStream();
        FileOutputStream fos=new FileOutputStream(new File("Running.txt"));
        byte[] b1=new byte[20];
        int len1;
        while((len1=is1.read(b1))!=-1){
            fos.write(b1,0,len1);
        }
        fos.close();
        is1.close();
    }
}
TestURL
原文地址:https://www.cnblogs.com/a842297171/p/5206602.html