您当前的位置: 首页 >  网络

梁云亮

暂无认证

  • 3浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

第十一章 网络编程

梁云亮 发布时间:2022-03-08 09:41:33 ,浏览量:3

网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来。

java.net 包中 JavaSE 的 API 包含有类和接口,它们提供低层次的通信细节。你可以直接使用这些类和接口,来专注于解决问题,而不用关注通信细节。

java.net 包中提供了两种常见的网络协议的支持:

TCP:TCP 是传输控制协议的缩写,它保障了两个应用程序之间的可靠通信。通常用于互联网协议,被称 TCP / IP。

UDP:UDP 是用户数据报协议的缩写,一个无连接的协议。提供了应用程序之间要发送的数据的数据包。

11.1 TCP/IP
  • server

    package cn.webrx;
    
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MyServer {
        public static void main(String[] args) throws UnknownHostException {
            List ss = new ArrayList();
            System.out.println(InetAddress.getLocalHost().getHostAddress());
            int port = 6636;
            try (ServerSocket s = new ServerSocket(port)) {
                while(true) {
                    Socket server = s.accept();
                    ss.add(server);
                    System.out.println("有人联网..." + server.getInetAddress() + "(" + server.getRemoteSocketAddress() + ")");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
  • client

    package cn.webrx;
    import java.io.IOException;
    import java.net.Socket;
    public class User {
        public static void main(String[] args) {
            try {
                Socket client = new Socket("192.168.11.191", 6636);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    

image-20210126153902633

  • 简单聊天程序

    package cn.webrx;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
    
    public class MyS {
        public static void main(String[] args) throws UnknownHostException {
            //服务端口号
            int port = 3366;
            //本机ip
            String ip = InetAddress.getLocalHost().getHostAddress();
            try {
                ServerSocket ss = new ServerSocket(port);
                Socket server = ss.accept();//网络监听
                System.out.println("有人联网");
    
                while (true) {
                    //发client信息
                    PrintWriter out = new PrintWriter(server.getOutputStream());
                    String info = String.format("[服务器:%s]:%s\r\n", ip, new Scanner(System.in).nextLine());
                    out.write(info);
                    out.flush();
    
    
                    //收client信息
                    InputStream is = server.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    info = br.readLine();
                    System.out.println(info);
    
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    package cn.webrx;
    
    import java.io.*;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.nio.charset.StandardCharsets;
    import java.util.Scanner;
    
    public class MyC {
        public static void main(String[] args) throws UnknownHostException {
            //服务端口号
            int port = 3366;
            String ip = InetAddress.getLocalHost().getHostAddress();
            try{
                Socket client = new Socket("localhost",port);
                while(true) {
                    //收client信息
                    InputStream is = client.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String info = br.readLine();
                    System.out.println(info);
    
                    OutputStream os = client.getOutputStream();
                    PrintWriter out = new PrintWriter(os);
                    //发client信息
                    info = String.format("[客户:%s]:%s \r\n",ip,new Scanner(System.in).nextLine());
                    out.write(info);
                    out.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    

    image-20210126164709541

  • 多线程实现聊天程序

    package cn.org;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
    
    public class MyServer {
        public static void main(String[] args) throws Exception {
            try{
                Scanner sc = new Scanner(System.in);
                ServerSocket s = new ServerSocket(6688);
                Socket server = s.accept();
                BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
                PrintWriter out = new PrintWriter(server.getOutputStream());
                new Thread(()->{
                    while(true){
                        out.print(sc.nextLine() + "\r\n");
                        out.flush();
                    }
                }).start();
                new Thread(()->{
                    while(true){
                        try{
                            System.out.println(br.readLine());
                        }catch(Exception e){
                            System.exit(0);
                        }
                    }
                }).start();
    
            }catch(Exception e){
                e.printStackTrace();
            }
    
        }
    }
    
    
    package cn.org;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
    
    public class MyClient {
        public static void main(String[] args) throws Exception {
            try{
                Scanner sc = new Scanner(System.in);
                Socket server = new Socket("localhost",6688);
                BufferedReader br = new BufferedReader(new InputStreamReader(server.getInputStream()));
                PrintWriter out = new PrintWriter(server.getOutputStream());
                new Thread(()->{
                    while(true){
                        out.print(sc.nextLine() + "\r\n");
                        out.flush();
                    }
                }).start();
                new Thread(()->{
                    while(true){
                        try{
                            System.out.println(br.readLine());
                        }catch(Exception e){
                            System.exit(0);
                        }
                    }
                }).start();
    
            }catch(Exception e){
                e.print
                    StackTrace();
            }
    
        }
    }
    
    
  • 简单gui 聊天程序

    package cn.webrx;
    
    import javax.swing.*;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.Socket;
    
    public class MyInput extends Thread {
    
        private Socket s;
        private JTextArea t;
        private BufferedReader br;
    
        public MyInput(Socket s, JTextArea t) {
            this.s = s;
            this.t = t;
        }
    
        public void run() {
            try {
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                while (true) {
                    String mess = br.readLine();
                    t.append(mess + "\r\n");
                }
            } catch (Exception e) {
                System.out.println(e.toString());
            }
    
        }
    }
    
    
    
    package cn.webrx;
    
    import java.awt.HeadlessException;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.ServerSocket;
    import java.net.Socket;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    
    public class Gs extends JFrame implements ActionListener, Runnable {
    
        private JTextArea txt = new JTextArea();
        private JPanel panel = new JPanel();
        private JTextField sendtxt = new JTextField(15);
        private JLabel info = new JLabel("信息:");
        private JButton sendbtn = new JButton("发送");
        private JButton connbtn = new JButton("启动");
        private JButton exitbtn = new JButton("停止");
        private ServerSocket ss;
        private Socket s;
        private JButton clearbtn = new JButton("清除");
    
        public Gs(String title) throws HeadlessException {
            super(title);
            this.setSize(500, 400);
            this.add(new JScrollPane(txt));
            panel.add(info);
            panel.add(sendtxt);
            panel.add(sendbtn);
            panel.add(connbtn);
            exitbtn.setEnabled(false);
            panel.add(exitbtn);
            panel.add(clearbtn);
            sendbtn.addActionListener(this);
            connbtn.addActionListener(this);
            exitbtn.addActionListener(this);
            clearbtn.addActionListener(this);
            txt.setEditable(false);
            this.add(panel, "South");
            this.setResizable(false);
            this.setLocationRelativeTo(null);
            this.setVisible(true);
            this.setDefaultCloseOperation(3);
        }
    
        public void actionPerformed(ActionEvent e) {
            JButton b = (JButton) e.getSource();
            if (b.getActionCommand().equals("发送")) {
                this.send();
            }
    
            if (b.getActionCommand().equals("启动")) {
                try {
                    int port = Integer.parseInt(JOptionPane.showInputDialog(this, "请输入服务器端口号", "8888"));
                    ss = new ServerSocket(port);
                    txt.append("服务器建立成功\n");
                    txt.append("IP:" + InetAddress.getLocalHost().getHostAddress() + "\n");
                    txt.append("Port:" + port + "\n");
    
                    new Thread(this).start();
    
                } catch (Exception ee) {
                    txt.append("端口号占用\n");
                }
                connbtn.setEnabled(false);
                exitbtn.setEnabled(true);
            }
            if (b.getActionCommand().equals("停止")) {
                exitbtn.setEnabled(false);
                connbtn.setEnabled(true);
                try {
                    ss.close();
                    JOptionPane.showMessageDialog(this, "服务器正常关闭", "关闭服务器", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception ex) {
                    System.out.println(ex.toString());
                }
            }
            if (b.getActionCommand().equals("清除")) {
                txt.setText("");
            }
        }
    
        public void send() {
            try {
                PrintWriter out = new PrintWriter(s.getOutputStream());
                out.write("服务器:" + sendtxt.getText().trim() + "\r\n");
                out.flush();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    
        public void run() {
            while (true) {
                try {
                    this.s = ss.accept();
                    txt.append("用户上线了\n");
                    new MyInput(s, txt).start();
                    break;
                } catch (Exception e) {
                    txt.append("服务器关闭了...\n");
                }
            }
        }
    
        public static void main(String[] args) {
            new Gs("服务器");
        }
    }
    
    package cn.webrx;
    
    import java.awt.HeadlessException;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    
    public class Gc extends JFrame implements ActionListener {
    
        private JTextArea txt = new JTextArea();
        private JPanel panel = new JPanel();
        private JTextField sendtxt = new JTextField("上线了", 15);
        private JLabel info = new JLabel("信息:");
        private JButton sendbtn = new JButton("发送");
        private JButton connbtn = new JButton("连接");
        private JButton clearbtn = new JButton("清除");
        private Socket s;
    
        public Gc(String title) throws HeadlessException {
            super(title);
            this.setSize(450, 400);
            this.add(new JScrollPane(txt));
            panel.add(info);
            panel.add(sendtxt);
            panel.add(sendbtn);
            panel.add(connbtn);
            panel.add(clearbtn);
            sendbtn.addActionListener(this);
            connbtn.addActionListener(this);
            clearbtn.addActionListener(this);
            this.add(panel, "South");
            this.setResizable(false);
            this.setLocationRelativeTo(null);
            this.setVisible(true);
            this.setDefaultCloseOperation(3);
        }
    
        public void actionPerformed(ActionEvent e) {
            JButton b = (JButton) e.getSource();
            if (b.getActionCommand().equals("连接")) {
                try {
                    String ip = JOptionPane.showInputDialog("请输入服务器的IP地址", InetAddress.getLocalHost().getHostAddress());
                    int port = Integer.parseInt(JOptionPane.showInputDialog("请输入端口号", "8888"));
                    s = new Socket(ip, port);
                    txt.append("连接成功\n");
                    new MyInput(s, txt).start();
                } catch (Exception ee) {
                    JOptionPane.showMessageDialog(this, "服务器没有启动或服务器IP及端口错误...");
                }
    
            }
            if (b.getActionCommand().equals("发送")) {
                this.send(this.s);
            }
            if (b.getActionCommand().equals("清除")) {
                txt.setText("");
            }
        }
    
        public void send(Socket s) {
            try {
                PrintWriter out = new PrintWriter(s.getOutputStream());
                out.write("用户:" + sendtxt.getText().trim() + "\r\n");
                out.flush();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    
        public static void main(String[] args) {
            new Gc("客户机");
        }
    }
    

image-20210127110747986

  • 网络传输文件

    package cn.org;
    
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Server {
        public static void main(String[] args) {
            int port = 3399;
            try {
                ServerSocket ss = new ServerSocket(port);
                while (true) {
                    Socket s = ss.accept();
                    InputStream is = s.getInputStream();
    
                    //读取字符串
                    byte[] bu = new byte[1];
                    StringBuilder str = new StringBuilder();
                    String text = "";
                    List list = new ArrayList();
                    while (text.indexOf("\r\n")  0) {
                        fos.write(buf, 0, len);
                    }
                    fos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    
    
    package cn.org;
    
    import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.nio.charset.StandardCharsets;
    
    public class Client {
        public static void main(String[] args) {
            int port = 3399;
            try {
                //建立文件输入流
                String fn = "c:/美女.jpg";
                String author = "赵六";
                File file = new File(fn);
                FileInputStream is = new FileInputStream(file);
                Socket s = new Socket("localhost",port);
                OutputStream os = s.getOutputStream();//字节流
    
                //传字符串
                String msg = String.format("%s,%s,%d\r\n",file.getName(),author,file.length());
                os.write(msg.getBytes(StandardCharsets.UTF_8));
    
    
                //传文件
                byte[] buf = new byte[1024];
                int len = 0;
                while((len=is.read(buf))>0){
                    os.write(buf,0,len);
                }
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    

image-20210127172314305

11.2 UDP

[Internet ](https://baike.baidu.com/item/Internet /272794)协议集支持一个无连接的传输协议,该协议称为用户数据报协议(UDP,User Datagram Protocol)。UDP 为应用程序提供了一种无需建立连接就可以发送封装的 IP 数据包的方法。RFC 768 [1] 描述了 UDP。

Internet 的传输层有两个主要协议,互为补充。无连接的是 UDP,它除了给应用程序发送数据包功能并允许它们在所需的层次上架构自己的协议之外,几乎没有做什么特别的事情。面向连接的是 TCP,该协议几乎做了所有的事情。 [2]

  • 接收信息

    /*
     * Copyright 2006-2021 webrx Group.
     */
    package cn.webrx.udp;
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    
    /**
     * 

    *

     * 
    * * @author webrx[webrx@126.com] * @version 1.0 * @date 2021-01-28 09:53:35 */ public class MsgReader { public static void main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket(8899); DatagramPacket dp = new DatagramPacket(new byte[1024], 1024); while (true) { ds.receive(dp); //有监听中断 System.out.println("接收到数据了..."); byte[] data = dp.getData(); int len = dp.getLength(); System.out.println(dp.getAddress()); System.out.println(dp.getPort()); System.out.println(len); System.out.println(new String(data, 0, len, "utf-8")); } } }
  • 发送信息

    /*
     * Copyright 2006-2021 webrx Group.
     */
    package cn.webrx.udp;
    
    import java.io.IOException;
    import java.net.*;
    import java.nio.charset.StandardCharsets;
    
    /**
     * 

    udp 发送信息 * * @author webrx[webrx@126.com] * @version 1.0 * @date 2021-01-28 09:47:59 */ public class MsgSend { public static void main(String[] args) throws IOException { String msg = "hello udp 信息数据..."; byte[] data = msg.getBytes(StandardCharsets.UTF_8); int len = data.length; DatagramSocket ds = new DatagramSocket(); DatagramPacket dp = new DatagramPacket(data,len, InetAddress.getByName("localhost"),8899); ds.send(dp); ds.close(); } }

    image-20210128104238261

  • udp传文件及字符串信息

    /*
     * Copyright 2006-2021 webrx Group.
     */
    package cn.webrx.udp;
    
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.nio.charset.StandardCharsets;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    /**
     * 

    *

     * 
    * * @author webrx[webrx@126.com] * @version 1.0 * @date 2021-01-28 10:49:13 */ public class FileReceive { public static void main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket(8899); byte[] data = new byte[1024 * 1024 * 10]; int len = data.length; DatagramPacket dp = new DatagramPacket(data, len); while (true) { ds.receive(dp); len = dp.getLength(); data = dp.getData(); String ip = dp.getAddress().getHostAddress().replace(".", "").replace("/", "") + ".jpg"; StringBuilder sr = new StringBuilder(); String text = ""; byte[] tt = new byte[1]; int index = 0; List list = new ArrayList(); while(text.indexOf("\r\n")
关注
打赏
1665409997
查看更多评论
0.0511s