Java 网络编程

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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Java 字符流

    是字符流通向字节流的桥梁:使用指定的 charset 将要向其写入的字符编码为字节

    用户7625070
  • Flink 流计算算子函数详解

    Flink 的算子函数和spark的大致一样,但是由于其是流处理的模式,所有还要有需要加强理解的地方

    用户7625070
  • Java 必备面试代码

    用户7625070
  • Java简单实现UDP和TCP

    TCP实现 TCP协议需要在双方之间建立连接,通过输入输出流来进行数据的交换,建立需要通过三次握手,断开需要四次挥手,保证了数据的完整性,但传输效率也会相应的降...

    李家酒馆酒保
  • 字符流出现乱码问题

    shimeath
  • AkShare-股票数据-板块行情

    新增板块行情的数据接口,主要可以查询当前的热点板块,该接口可以查询实时的板块行情数据。

    AkShare
  • Flutter中的操作提示

    在前面的文章中我们学习了Flutter中输入以及选择控件的用法,借助于这些组件大家可以完成很多常用的功能,但是他不能及时在用户操作后完成相应的界面提示,所以今天...

    flyou
  • 【Flutter 专题】07 您搭好【登录】页面了么?

    和尚最近在利用业余时间学习 Flutter,还真的是值得研究。和尚觉得学习一门技术最好的方式就是动手,在实践过程中结合官网文档才能更快的学习和理解。...

    阿策
  • 【Flutter 专题】08 小小优化【登录】页面

    和尚前两天花了很久才搭建了一个最简单的【登录】页面,但依然还有很多需要优化的地方,和尚又花了很久的时间尝试做了一点点的优化,仅针对优化的部分简单整理...

    阿策
  • Flutter 简易新闻项目目标效果对比简介代码代码地址

    使用flutter快速开发 Android 和 iOS 的简易的新闻客户端 API使用的是 showapi(易源数据) 加载热门微信文章

    gwk_iOS

扫码关注云+社区

领取腾讯云代金券