美文网首页
【Java梳理】网络操作

【Java梳理】网络操作

作者: 田文健 | 来源:发表于2017-12-19 16:47 被阅读0次

    1.使用TCP协议
    Tcp协议是一个保证送达的网络层传输协议,它的特点是保证数据完整的送达。
    监听TCP端口,编写一个TCP服务器

    public static void main(String[] args){
    
            try {
                System.out.println("server start...");
                ServerSocket ss = new ServerSocket(10005);
                Socket s = ss.accept();
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                String receiveDataStr = null;
                while ((receiveDataStr = br.readLine()) != null) {
                    System.out.println("receive data:" + receiveDataStr);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    

    发送TCP数据,TCP客户端

    public static void main(String[] args){
            try {
                System.out.println("client start...");
                Socket s = new Socket("127.0.0.1", 10005);
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                String sendDataStr = null;
                while ((sendDataStr = br.readLine()) != null) {
                    if (sendDataStr.equals("end")){
                        break;
                    }
    
                    bw.write(sendDataStr);
                    bw.newLine();
                    bw.flush();
                }
                bw.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    

    同时运行上面两段代码,在client的控制台中输入字符串并回车,server可以收到并打印出来,这是最简单的TCP程序。

    2使用UDP协议

    Udp协议是只管发送,不保证数据送达的协议实现。
    监听端口,使用12000作为收发数据的端口

    public static void main(String[] args){
    
            try (DatagramSocket socket = new DatagramSocket(12000)) {
                while (true) {
                    try {
                        DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
                        socket.receive(request);
    
                        String daytime = new Date().toString();
                        byte[] data = daytime.getBytes("ASCII");
                        DatagramPacket response = new DatagramPacket(data, data.length, request.getAddress(), request.getPort());
                        socket.send(response);
                        System.out.println(daytime + " " + request.getAddress());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    发送数据

     public static void main(String[] args){
            //传入0表示让操作系统分配一个端口号
            try (DatagramSocket socket = new DatagramSocket(0)) {
                socket.setSoTimeout(10000);
                InetAddress host = InetAddress.getByName("127.0.0.1");
                //指定包要发送的目的地
                DatagramPacket request = new DatagramPacket(new byte[1], 1, host, 12000);
                //为接受的数据包创建空间
                DatagramPacket response = new DatagramPacket(new byte[1024], 1024);
                socket.send(request);
                socket.receive(response);
                String result = new String(response.getData(), 0, response.getLength(), "ASCII");
                System.out.println(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    

    DatagramSocket 表示发送和接收数据包的socket对象,DatagramPacket 则是数据报文。关于TCP和UDP的更详细介绍请参考 计算机网络原理

    相关文章

      网友评论

          本文标题:【Java梳理】网络操作

          本文链接:https://www.haomeiwen.com/subject/dagwbxtx.html