Java 网络编程

作者: Tim在路上 | 来源:发表于2018-11-01 23:30 被阅读0次

    1.获取主机名,IP地址

      public static void main(String[] args) throws UnknownHostException {
            
              InetAddress adress = InetAddress.getByName("n");
              String ipname = adress.getHostAddress();
              String Hostname = adress.getHostName();
              System.out.println(ipname+"---"+Hostname);
        }
    

    2.UDP编程

    客户端

    /*
         * 1.创建发送的Socket对象
         * 2.创建数据并打包
         * 3.调用Socket的发送方法发送数据包
         * 4.释放资源
         * 可以运行
         */
          public static void main(String[] args) throws IOException {
            
              //创建Socket对象 
              DatagramSocket ds = new  DatagramSocket();
              //创建并打包数据
              //DatagramPacket(byte[] buf,int length,InetAddress address,int port),数据包的格式
              //1.创建要发送的字节数组
              byte[] bs = "国芳小果果".getBytes();
              //2.得到数据的长度
              int len = bs.length;
              //获得IP地址
              InetAddress address = InetAddress.getByName("n");
              //设置端口号
              int port = 8888;      
              //创建数据包
              DatagramPacket dp = new DatagramPacket(bs, len, address, port); 
              //调用Socket的发送方法发送数据包
              //send(DatagramPacket p)
              ds.send(dp);
              //释放资源
              ds.close();
    
        }
    服务端
     /*
           * 1.创建连接的Socket对象
           * 2.创建接受数据对象
           * 2.接受数据包
           * 3.解析数据并显示在控制台
           * 3.释放资源
           */
          public static void main(String[] args) throws IOException {
            //创建UDP编程的Socket,接受数据时必须指定端口号
              DatagramSocket ds = new DatagramSocket(8888);
            //创建用于接受数据的数据包
              byte[] bs = new byte[1024];
              DatagramPacket dp = new DatagramPacket(bs, 1024);
            //接受数据
              ds.receive(dp);
              System.out.println(new String(bs));
              //释放资源
              ds.close();
        }
    

    3.UDP实现键盘数据的传输,同时使用广播IP地址实现一对多传输

    public class SocketSend {
      /*
       * 数据来自于键盘录入
       * 键盘录入数据要自己控制录入结束
       * UDP的广播IP是255.255.255.255
       */
        public static void main(String[] args) throws IOException {
              //创建Socket对象
            DatagramSocket ds = new  DatagramSocket();
              //封装键盘录入数据
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = null;
            while((line = br.readLine())!=null){
                if(line.equals("886")){ //如果送入数据等于886,停止输入
                    break;
                }
                //创建数据并打包
                byte[] bs = line.getBytes();
                DatagramPacket dp = new DatagramPacket(bs, bs.length,InetAddress.getByName("255.255.255.255"),10087);
                
                //发送数据
                ds.send(dp);
            }
            ds.close();
        }
    }
    
    public class SocketReceive {
         
          public static void main(String[] args) throws IOException {
             
              //创建Socket接受类
              DatagramSocket ds = new DatagramSocket(10087);
              while(true){
              //创建一个包裹
              byte[] bs = new byte[1024];
              DatagramPacket dp = new DatagramPacket(bs, bs.length);
              //接受数据
              ds.receive(dp);
              //解析数据
              String ip = dp.getAddress().getHostAddress();
              String s  = new String(dp.getData(),0,dp.getData().length);
              System.out.println("from"+ip+"data is"+s);
              }
        }
    
    }
    

    4.通过多线程实现在同框进行聊天

    public class chatRoom {
        /*
         * 通过多线程改变程序我就可以在一个窗口里进行聊天了
         */
          public static void main(String[] args) throws IOException {
              //发送数据
              DatagramSocket dsSend = new DatagramSocket();
              DatagramSocket dsRece = new DatagramSocket(10026);
              //多线程启动接收机
              SendThread st = new SendThread(dsSend);
              ReceiveThread rt = new ReceiveThread(dsRece);
              
              //创建线程对线
              Thread t1 = new Thread(st);
              Thread t2 = new  Thread(rt);
              t1.setPriority(10);
              //启动线程
              t1.start();
              t2.start();
              
              
        }
    
    }
    public class SendThread implements Runnable{
     
        private DatagramSocket ds;
        
       public SendThread(DatagramSocket ds) {
            this.ds = ds;
        }
        @Override
        public void run() {
            try{
                
              //封装键盘录入数据
                    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                    String line = null;
                        while((line = br.readLine())!=null){
                            if(line.equals("886")){ //如果送入数据等于886,停止输入
                                break;
                            }
                            //创建数据并打包
                            byte[] bs = line.getBytes();
                            DatagramPacket dp = new DatagramPacket(bs, bs.length,InetAddress.getByName("255.255.255.255"),10026);
                            ds.send(dp);
                        }
                    
                    ds.close();
            }catch(IOException ioe){
                ioe.printStackTrace();
            }
            
        }
    
    }
    public class ReceiveThread implements Runnable{
     
        private DatagramSocket ds;
        
        public ReceiveThread(DatagramSocket ds){
            this.ds =ds;
        }
        @Override
        public void run() {
            try{
              while(true){
                  //创建一个包裹
                  byte[] bs = new byte[1024];
                  DatagramPacket dp = new DatagramPacket(bs, bs.length);
                  //接受数据
                
                    ds.receive(dp);
                  //解析数据
                  String ip = dp.getAddress().getHostAddress();
                  String s  = new String(dp.getData(),0,dp.getData().length);
                  System.out.println("from"+ip+"data is"+s);
                  System.out.println();
                  }
            }
            catch(IOException ioe){
                ioe.printStackTrace();
            }
        }
    

    5实现TCP的网络协议编程

    public class ClientDemo {
        
         public static void main(String[] args) throws IOException {
              //创建客户端套接字
             Socket s = new Socket("n", 22222);
             //封装键盘流
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             //创建写入流
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
             //创建临时存储
             String line = null;
             while((line=br.readLine())!=null){
                 if("over".equals(line)){
                     break;
                 }
                 bw.write(line);
                 bw.newLine();
                 bw.flush();
             }
             s.close();
             
             
        }
    
    }
    public class ServerDemo {
         
         public static void main(String[] args) throws IOException {
             //创建服务器套接字
             ServerSocket ss = new ServerSocket(22222);
             //开启监听
             Socket s = ss.accept();
             //创建高效读取类,字符字节转换类,套接字字节通道流
             BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    //       //创建反馈流
    //       BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
             //创建临时存储
             String line = null;
             //提供读取
             while((line=br.readLine())!=null){
                System.out.println(line);
             }
             s.close(); 
        }
    
    }
    
    
    }
    

    6.写到文件

     public static void main(String[] args) throws IOException {
             //创建服务器套接字
             ServerSocket ss = new ServerSocket(22222);
             //开启监听
             Socket s = ss.accept();
             //创建高效读取类,字符字节转换类,套接字字节通道流
             BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    //       //创建文本流
             BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
             //创建临时存储
             String line = null;
             //提供读取
             while((line=br.readLine())!=null){
                System.out.println(line);
                bw.write(line);
                bw.newLine();
                bw.flush();
             }
             s.close(); 
             bw.close();
        }
    

    7.从文件中读取,在服务器中输出

    public class ClientDemo {
        public static void main(String[] args) throws IOException {
             //创建客户端套接字
            Socket s = new Socket("n", 22222);
            //封装文本文件的读取路径
            BufferedReader br = new BufferedReader(new FileReader("SocketSend.java"));
            //创建输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            String line = null;
            while((line = br.readLine())!=null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
            br.close();
            s.close();
            
        }
    
    }
    

    8,文件的上传带反馈

    public class ClientDemo {
        public static void main(String[] args) throws IOException {
             //创建客户端套接字
            Socket s = new Socket("n", 22222);
            //封装文本文件的读取路径
            BufferedReader br = new BufferedReader(new FileReader("SocketSend.java"));
            //创建输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            //读取流
            BufferedReader brs = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String line = null;
            while((line = br.readLine())!=null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
            s.shutdownOutput();//提示输入结束
            
            String str = brs.readLine();
            System.err.println(str);
            //释放资源
            br.close();
            s.close();
            
        }
    
    }
    

    //服务端

    public class ServerDemo {
         
          public static void main(String[] args) throws IOException {
             //创建服务器套接字
              ServerSocket ss = new ServerSocket(22222);
              //开启监听
              Socket s = ss.accept();
              //创建读取输入流
              BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
              //创建文本输出流
              BufferedWriter bw = new BufferedWriter(new FileWriter("CopyAction.java"));
              String line = null;
              while((line=br.readLine())!=null){ 
                  bw.write(line);
                  bw.newLine();
                  bw.flush();
              }
              BufferedWriter bws = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
              bws.write("我收到了");
              bws.newLine();
              bws.flush();
              
              
              //释放资源
              bws.close();
              bw.close();
              s.close();
        }
    
    }
    

    9.上传图片

    public class uploadClient {
          
        public static void main(String[] args) throws IOException {
              //创建客户端套接字Socket
            Socket s = new Socket("n",9999);
             //封装图片
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream
                    (new File("C:\\Users\\DELL\\Pictures\\2015-04-25\\生活\\1.jpg")));
            //创建写入通道
            BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
            //创建读取
            byte[] bs = new byte[1024];
            int len = 0;
            while((len = bis.read(bs))!=-1){
                bos.write(bs,0,len);
            }
            s.shutdownOutput();
            //创建读取流
            String line = null;
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            line = br.readLine();
            System.err.println(line);
            //释放资源
            s.close();
            bis.close();
            
        }
    
    }
    public class uploadServer {
        public static void main(String[] args) throws IOException {
             //创建服务器端套接字socket
            ServerSocket ss = new ServerSocket(9999);
            //创建监听
            Socket s = ss.accept();
            //创建字节读取流
            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
            //创建图片复制流
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("mn.jpg"));
            //读取数组
            byte[] bs = new byte[1024];
            int len = 0;
            while((len=bis.read(bs))!=-1){
                bos.write(bs,0,len);
            }
            
            //创建反馈流
            OutputStream os = s.getOutputStream();
            os.write("我收到了".getBytes());
            
            //释放资源
            os.close();
            s.close();
                    
        }
    
    }
    

    10.多客户端与一服务器通信

    public class ClientDemo {
        public static void main(String[] args) throws IOException {
             //创建客户端套接字
            Socket s = new Socket("n", 11111);
            //封装文本文件的读取路径
            BufferedReader br = new BufferedReader(new FileReader("ServerDemo.java"));
            //创建输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            //读取流
            BufferedReader brs = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String line = null;
            while((line = br.readLine())!=null){
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
            s.shutdownOutput();
            
            String str = brs.readLine();
            System.err.println(str);
            //释放资源
            br.close();
            s.close();
            
        }
    
    }
    public class UserThread implements Runnable{
        private Socket s;
        
        public UserThread(Socket s) {
            this.s = s;
        }
        @Override
        public void run() {
            try{
                 //创建读取输入流
                  BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                  //创建文本输出流
                  BufferedWriter bw = new BufferedWriter(new FileWriter("CopyAction.java"));
                  String line = null;
                  while((line=br.readLine())!=null){ 
                      bw.write(line);
                      bw.newLine();
                      bw.flush();
                  }
                  BufferedWriter bws = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                  bws.write("我收到了");
                  bws.newLine();
                  bws.flush();
                  
                  
                  //释放资源
                  bws.close();
                  bw.close();
                  s.close();
            }catch(IOException ioe){
                ioe.printStackTrace();
            }
        }
    
    }
    public class UPloadServer {
          public static void main(String[] args) throws IOException {
            
              ServerSocket ss = new ServerSocket(11111);
              while(true){
                  Socket s = ss.accept();
                  new Thread(new UserThread(s)).start();
              }
        }
    }
    
    网络编程.jpeg

    相关文章

      网友评论

        本文标题:Java 网络编程

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