JavaSE——网络编程

网络编程的两个要素

  1. IP
public static void main(String[] args) throws IOException {
    InetAddress address = Inet4Address.getByName("www.baidu.com");
    System.out.println(address);
    System.out.println(address.getHostName());//获得域名
    System.out.println(address.getHostAddress());//获得ip地址
    InetAddress localHost = Inet4Address.getLocalHost();
    System.out.println(localHost);
}
  1. 端口号

0-1023公认端口
1024-49151注册端口 分配给用户进程或应用程序
49152-65535 动态、私有端口

  1. 网络协议

1、TCP
先建立TCP连接,采用三次握手,进行通信的两个应用进程:客户端和服务端
在连接中可以进行大数据量的传输,传输完毕需要释放已经建立的连接,效率低。
2、UDP
将数据、源和目的封装成数据包,不需要建立连接,每个数据包的大小限制在64k以内,可以广播发送,发送数据结束时无需释放资源、开销小速度快。

在这里插入图片描述

TCP示例1:服务端和客户端本机通信

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class test{
    @Test
    public void client(){
        Socket socket = null;
        OutputStream osm = null;
        try {
            InetAddress inet = Inet4Address.getByName("127.0.0.1");
            socket = new Socket(inet, 8899);
            osm = socket.getOutputStream();
            osm.write("这里是客户端".getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(osm!=null) {
                try {
                    osm.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if(socket!=null) {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }


    }
    @Test
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            serverSocket = new ServerSocket(8899);
            accept = serverSocket.accept();
            is = accept.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] cbuf = new byte[5];
            int len;
            while((len=is.read(cbuf))!=-1){
                baos.write(cbuf,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(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept!=null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

TCP示例2:将客户端发送的图片保存到服务器端

public class test{
    @Test
    public void client(){
        Socket socket = null;
        OutputStream os = null;
        BufferedInputStream bis = null;
        InputStream is=null;
        ByteArrayOutputStream baos=null;
        try {
            socket = new Socket(Inet4Address.getLocalHost(),8809);
            os = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(new File("bg.jpg"));
            bis = new BufferedInputStream(fis);
            byte[] cbuf = new byte[1024];
            int len;
            while((len=bis.read(cbuf))!=-1){
                os.write(cbuf,0,len);
            }
            socket.shutdownOutput();//发送端发送完了终止发送
            is = socket.getInputStream();
            baos = new ByteArrayOutputStream();
            byte[] buf = new byte[20];
            int l;
            while((l=is.read(buf))!=-1){
                baos.write(buf,0,l);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(bis!=null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(baos!=null){
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
        
    @Test
    public void server(){
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream is = null;
        FileOutputStream fos = null;
        OutputStream os=null;
        try {
            serverSocket = new ServerSocket(8809);
            accept = serverSocket.accept();
            is = accept.getInputStream();
            fos = new FileOutputStream("bg1.jpg");
            byte[] cbuf = new byte[1024];
            int len;
            while((len=is.read(cbuf))!=-1){
                fos.write(cbuf,0,len);
            }
            os = accept.getOutputStream();
            os.write("图片已经收到了".getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(serverSocket!=null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

UDP示例

public class test{
    @Test
    public void client() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String str="UDP的传送方式";
        byte[] data=str.getBytes(StandardCharsets.UTF_8);
        InetAddress inet = Inet4Address.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, 8809);
        socket.send(packet);
        socket.close();
    }
        
    @Test
    public void server() throws IOException{
        DatagramSocket socket = new DatagramSocket(8809);
        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();
    }
}

URL编程

在这里插入图片描述

//URL常用方法
public class test{
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost/examples/bg.jpg");
        System.out.println(url.getProtocol());
        System.out.println(url.getHost());
        System.out.println(url.getPort());
        System.out.println(url.getPath());
        System.out.println(url.getFile());
        System.out.println(url.getQuery());
    }
}
public static void main(String[] args){
    HttpURLConnection urlConnection = null;
    InputStream is = null;
    FileOutputStream fos = null;
    try {
        URL url = new URL("http://localhost/examples/bg.jpg");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        is = urlConnection.getInputStream();
        fos = new FileOutputStream("bg2.jpg");
        byte[] cbuf = new byte[20];
        int len;
        while((len=is.read(cbuf))!=-1){
            fos.write(cbuf,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fos!=null){
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(is!=null){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(urlConnection!=null){
            urlConnection.disconnect();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaSE网络编程采用的是基于TCP/IP协议的网络模型。这个模型包括客户端和服务器端两部分。客户端通过套接字(Socket)与服务器建立连接,服务器则监听客户端的连接请求并进行响应。 在Java中,可以使用Socket类和ServerSocket类来实现网络编程。Socket类用于建立客户端与服务器之间的通信连接,而ServerSocket类则用于创建服务器端的套接字,监听并接受客户端的连接请求。 客户端通过创建Socket对象,指定服务器的IP地址和端口号,然后通过Socket对象的方法与服务器进行通信。服务器端通过创建ServerSocket对象,指定服务器要监听的端口号,并通过accept()方法接受客户端的连接请求。一旦建立了连接,客户端和服务器端就可以通过输入流和输出流来进行数据的传输。 网络模型是基于TCP/IP协议的,因此可以使用Java的InputStream和OutputStream来进行数据的读写。客户端可以通过InputStream从服务器端接收数据,通过OutputStream向服务器端发送数据。服务器端则可以通过InputStream接收客户端发送的数据,通过OutputStream向客户端发送数据。 总结来说,JavaSE网络编程采用的是基于TCP/IP协议的网络模型,通过Socket和ServerSocket来实现客户端和服务器端之间的通信。通过InputStream和OutputStream来进行数据的读写。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [JavaSE——网络编程](https://blog.csdn.net/yzl1293346757/article/details/126192384)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [JavaSE学习——网络编程](https://blog.csdn.net/Demon_and_Angle_/article/details/126387829)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值