跳至主要內容

16、网络编程

T4makojava基础语法javasocket大约 4 分钟

网络编程

网络编程中的两个要素:

  • IP和端口号
  • 网络通信协议:TCP/IP

InetAdress类:

  • java使用InetAddress类代表IP
  • 获取InetAddress实例:getLocalHost()getByName()
  • 获取IP:getHostAddress
  • 获取IP地址的主机名:geHostName()
  • 端口号与IP地址的组合得出一个网络套接字:socket

image-20220725201127672

image-20220725201051851

1、实现TCP网络编程

客户端Socket:

  1. 创建 Socket:
    根据指定服务端的 IP 地址或端口号构造 Socket 类对象。
    若服务器端响应,则建立客户端到服务器的通信线路。
    若连接失败,会出现异常。
  2. 打开连接到 Socket 的输入/出流:
    使用 getInputStream() 方法获得输入流
    使用 getOutputStream() 方法获得输出流,进行数据传输
  3. 对 Socket 进行读/写操作:
    通过输入流读取服务器放入线路的信息(但不能读取自己放入线路的信息),通过输出流将信息写入线程。
    4、关闭 Socket: 断开连接,释放线路

服务端:

  1. 调用ServerSocket(int port) : 创建一个服务器端套接字,并绑定到指定端口上。监听客户端的请求。
  2. 调用accept(): 接受连接,返回通信套接字对象。
  3. 调用该Socket类对象的 getOutputStream()getInputStream (): 获取输出流和输入流,开始网络数据的发送和接收。
  4. 关闭ServerSocket和Socket对象: 客户端访问结束,关闭通信套接字。
 /* 实现TCP网络编程
 * 例一:客户端发送信息给服务端,服务端将数据显示在控制台
 */
public class TCPTest1 {
    //客户端
    @Test
    public void client(){
        Socket socket = null;
        OutputStream os = null;
        try {
            //1、创建socket对象,指明服务器的ip和端口号
            InetAddress inet = InetAddress.getByName("192.168.80.1");
            socket = new Socket(inet,8899);
            //2、获取一个输出流、用于输出数据
            os = socket.getOutputStream();
            //3、写出数据造作
            os.write("hi,i am client".getBytes());
        } catch (IOException e) {
            //4、资源关闭
            e.printStackTrace();
        } finally {
            if(os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    @Test
    public void server(){
        ServerSocket ss = null;
        Socket socket = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //1、创建服务器端的socket,指明自己的端口号
            ss = new ServerSocket(8899);
            //2、调用accept方法,表示接受来自客户端的socket
            socket = ss.accept();
            //3、获取输入流
            is = socket.getInputStream();

            //不介意这样写,可能会乱码
//        byte[] buffer = new byte[20];
//        int len;
//        while((len = is.read(buffer) != -1){
//            String str = new String(buffer,0,len);
//            System.out.print(str);

            //4、读取输入流的数据
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[5];
            int len;
            while ((len = is.read(buffer)) != -1){
                baos.write(buffer,0,len);
            }
            System.out.println(baos.toString());
            System.out.println("收到了来自于:"+socket.getInetAddress().getHostAddress()+"的数据");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5、关闭资源
            if(baos != null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(ss != null){
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
/* 实现TCP网络编程
 * 例题2:客户端发送文件给服务端,服务端将文件保存在本地
 */
public class TCPTest2 {
    //注:异常处理任应使用try-catch-finally
    @Test
    public void client() throws IOException {
        //
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9090);
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream(new File("tamakoTest1.jpg"));
        //
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //
        fis.close();
        os.close();
        socket.close();


    }
    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(9090);

        Socket socket = ss.accept();

        InputStream is = socket.getInputStream();

        FileOutputStream fos = new FileOutputStream(new File("tamakoTest2.jpg"));

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

        fos.close();
        is.close();
        socket.close();
        ss.close();
    }
}
/* 例题三:客户端发送文件给服务端,服务端保存至本地,返回“发送成功”给客户端,并关闭相应连接
 */
public class TCPTest3 {

    @Test
    public void client() throws IOException {
        //
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9900);
        OutputStream os = socket.getOutputStream();
        FileInputStream fis = new FileInputStream("tamakoTest.jpg");
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        //关闭数据输出
        socket.shutdownOutput();

        //5、接受来自于服务器端的,并显示到控制台上
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer2 = new byte[20];
        int len1;
        while ((len1 = is.read(buffer2)) != -1){
            baos.write(buffer,0,len1);
        }
        System.out.println(baos.toString());
        //
        fis.close();
        os.close();
        socket.close();
        is.close();
        baos.close();

    }

    @Test
    public void server() throws IOException {
        ServerSocket ss = new ServerSocket(9900);
        Socket socket = ss.accept();
        System.out.println("conncetion!");

        InputStream is = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File("tamakoTest3.jpg"));

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

        System.out.println("complete");
        //服务器端给与客户端反馈
        OutputStream os = socket.getOutputStream();
        os.write("hello".getBytes());
        os.flush();
        //
        os.close();
        fos.close();
        is.close();
        socket.close();
        ss.close();

    }
}

2、实现UDP网络编程

public class UDPTest {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String str = "UDP function";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
        socket.send(packet);
        socket.close();
    }
    //接收端
    @Test
    public void receiver() throws IOException {
        DatagramSocket socket = new DatagramSocket(9090);
        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()));
        socket.close();
    }
}

image-20220725213949092

image-20220725214001092

3、URL网络编程

URL:统一资源定位符
包括:协议 主机名 端口号 资源地址 参数列表

public class URLTest {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
            System.out.println(url.getProtocol());
            System.out.println(url.getHost());
            System.out.println(url.getPath());
            System.out.println(url.getFile());
            System.out.println(url.getQuery());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

image-20220725215055140

public class URLTest1 {
    public static void main(String[] args) {
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");

            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.connect();

            is = urlConnection.getInputStream();

            fos = new FileOutputStream("day10\\tamakoTest4.txt");

            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(urlConnection != null)
            urlConnection.disconnect();
        }
    }
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5