Java笔记----TCP、UDP、URL示例

  1. 在Java中使用InetAddress类代表IP
  2. 本地回路地址: 127.0.0.1 对应着: localhost
  3. 如何实例化InetAddress:两个方法:getByName(String host) 、getLocalHost()
    • 两个常用方法: getHostName() / getHostAddress()
  4. 端口号:正在计算机上运行的进程。
    • 要求:不同的进程有不同的端口号
    • 范围:被规定为一个16位的整数0~65535。
一、TCP

步骤:
客户端:

  1. 创建客户端InetAddress
  2. 创建客户端Socket,指明端口
  3. 创建输出流并存入数据

服务器端:

  1. 创建服务器端ServerSocket,指明端口
  2. 调用accept()接收来自客户端的socket
  3. 获取输入流并操作其中数据

示例

import org.junit.Test;

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

public class TCPTest {
    @Test
    public void client(){
        Socket socket = null;
        OutputStream os = null;
        try {
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            socket = new Socket(inet,8899);
            os = socket.getOutputStream();
            os.write("你好,我是客户端".getBytes());
            ;
        } catch (IOException e) {
            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 {
            ss = new ServerSocket(8899);
            socket = ss.accept();
            is = socket.getInputStream();

//        //可能会有乱码,建议使用下面的ByteArrayOutputStream
//        byte[] buffer = new byte[20];
//        int len ;
//        while((len = is.read(buffer))!=-1){
//            String str = new String(buffer,0,len);
//            System.out.println(str);
//        }
            //读取输入流中的数据
            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());
        } 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 (socket == null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ss == null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


练练手:客户端发文件到服务器,服务器保存到本地,并给客户端反馈发送成功,客户端输出信息到控制台。
简易实现,没有解决异常,只是抛出

import org.junit.Test;

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

public class DemoTure {
    @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("星空.png"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }
        //read为阻塞式方法,不会自己结束循环
        //关闭数据的输出
        socket.shutdownOutput();

        //接收服务器的数据,显示到控制台
        InputStream is = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bufferr = new byte[20];
        int len1;
        while ((len1 = is.read(bufferr)) != -1) {
            baos.write(bufferr, 0, len1);
        }

        System.out.println(baos.toString());

        baos.close();
        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("星空2.png"));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        System.out.println("图片传输完成");

        //服务器端反馈给客户端
        OutputStream os = socket.getOutputStream();
        os.write("收到".getBytes());

        fos.close();
        is.close();
        socket.close();
        ss.close();
        os.close();
    }
}

二、UDP示例

UDP中注意Socket和Package

import org.junit.Test;

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

public class UDPTest {
    //发送端
    @Test
    public void sender() throws IOException {
        DatagramSocket socket = new DatagramSocket();
        String str = "我是UDP方式发送的消息";
        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();
    }
}

三、URL常用方法和示例

常用方法

public class URLTest {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://localhost:8080/examples/beauty.jpg?username=Tom");
            //public String getProtocol();获取该URL的协议名
            System.out.println(url.getProtocol());
            
            //public String getHost( );//获取该URL的主机名
            System.out.println(url.getHost());
            
            //public String getPort( );获取该URL的端口号          
            System.out.println(url.getPort());
            
            //public String getPath( );获取该URL的文件路径
            System.out.println(url.getPath());
            
            //public String getQuery();获取该URL的查询名
            System. out . println(url.getQuery());
            
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

示例:从网上下载一张图片

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

public class URLTest1 {
    public static void main(String[] args) {
        HttpURLConnection urlConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("https://desk-fd.zol-img.com.cn/t_s960x600c5/g2/M00/02/07/ChMlWV8OoO2IIUN6ABRl6dsm5NUAAP-7gAvnw4AFGYB199.jpg");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();

            is = urlConnection.getInputStream();
            fos = new FileOutputStream("NetworkPrograming//beauty.png");
            //注意main()中,文件路径是基于Project

            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 (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
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值