java基础增强:网络编程TcpUdp案例

Posted zdl9857

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java基础增强:网络编程TcpUdp案例相关的知识,希望对你有一定的参考价值。

一入编程深似海,从此妹子是路人。

1、Udp的客户端,服务端-----DatagramSocket

通过Udp协议编写一个群聊室,具体实现代码如下:

package day.by.day.udp.charroom;
//客户端代码
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class Client implements Runnable{

    @Override
    public void run() {
      //点名DatagramSocket快递员
        try {
            DatagramSocket ds = new DatagramSocket();
            //书写包裹信息,快递单寄件人信息
            Scanner sc = new Scanner(System.in);
            String str;
            while( (str = sc.nextLine())!=null) {
              //包装包裹,和收件地址,快递号
                DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length,
                        InetAddress.getByName("127.0.0.1"),8888);  
                //给快递员送走
                ds.send(dp);
                if( "over".equals(str)) { 
                    break;
                }
            }
            ds.close();
            sc.close();
            
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
    
    
}
package day.by.day.udp.charroom;
//服务端代码
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class sever implements Runnable{

    @Override
    public void run() {
        try {
            DatagramSocket ds = new DatagramSocket(8888);
            DatagramPacket dp = new DatagramPacket(new byte[64*1024], 64*1024);
            while( true) { 
                ds.receive(dp);
                byte[] bs = dp.getData();
                int len = dp.getLength();
                InetAddress ip = dp.getAddress();
                System.out.println(ip.getHostAddress()+":"+new String(bs,0,len));
            }
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

}
package day.by.day.udp.charroom;
//执行程序
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Run {

    public static void main(String[] args) throws Exception {
        //用线程池的方法
        ExecutorService pool = Executors.newCachedThreadPool();
        pool.execute(new Client());
        Thread.sleep(10);
        pool.execute(new sever());
    }

}

2、Tcp借助字节流传输数据,客户端---Socker,  服务端----ServerSocket

通过Tcp协议实现多级文件夹的拷贝,具体实现代码如下:

package day.by.day.tcp.copyflioder;
//客户端代码
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class CopyFlioderTcpClient {

    public static void main(String[] args) {
        //获取文件
        File folder = new File("d:/pic",".jpg");
        String[] list = folder.list();
        for (String file : list) {
            
            try {
                Socket s = new Socket("127.0.0.1",8888);
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
                //开始读取文件信息
                byte[] brr = new byte[1024];
                int len;
                while((len = bis.read(brr))!=-1) { 
                    bos.write(brr,0,len);
                    bos.flush();
                }
                s.shutdownOutput();
                
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                System.out.println(br.readLine());
                bis.close();
                s.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
        
    }

}
package day.by.day.tcp.copyflioder;
//服务端代码
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

import day.by.day.shangchuantupian.test.SeverSocker;

public class CopyFiloderSever {

    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(8888);
            while( true) { 
                Socket s = ss.accept();
                File file = new File("d:/", System.currentTimeMillis()+".jpg");
                BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                byte[] brr = new byte[1024];
                int len;
                while( ( len = bis.read(brr))!=-1) { 
                    bos.write(brr,0,len);
                    bos.flush();
                }
                
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                bw.write("chenggong");
                bw.newLine();
                bw.flush();
                bos.close();
                s.close();
                ss.close();
                
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

3、Tcp借助字节流传输数据,客户端---Socker,  服务端----ServerSocket

通过Tcp协议实现图片的上传,具体实现代码如下:

package day.by.day.shangchuantupian.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端代码
public class SockerClient {

    public static void main(String[] args) {
        //创建socket对象获取IP地址和端口号
      try {
        Socket s = new Socket("127.0.0.1",8888);
        //创建缓冲字节输入流,用来获取本地图片的字节信息
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\Usersi\Desktop/222.jpg"));
        //在IO流池中获取输出字节流
        BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
        //开始读取图片信息
        //创建缓冲数组
       byte[] brr = new byte[1024];
       int len;
       while( ( len = bis.read(brr))!=-1) { 
           bos.write(brr);
           bos.flush();
       }
       s.shutdownOutput();
       
       //就接受服务端返回的信息
       //创建缓冲输入字符流
       BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
       System.out.println( br.readLine());
       s.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

}
package day.by.day.shangchuantupian.test;
//服务端代码
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class SeverSocker implements Runnable{
    private Socket s;
    
    public SeverSocker(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        //创建缓冲字节输入流
        try {
            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
            //创建缓冲字节输出流,用于生命复制图片的地址
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:/"+System.currentTimeMillis()+".jpg"));
            //读取流中的图片信息
            //定义缓冲数组
            byte[] brr = new byte[1024];
            int len;
            while( ( len = bis.read(brr))!=-1) { 
                bos.write(brr,0,len);
                bos.flush();
            }
            
            //向客户端返回信息
            //定义缓冲字符输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
            s.close();
        } catch (Exception e) {
            //处理异常
            System.out.println("上传失败");
            if( null != s) { 
                try {
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                    bw.write("上传成功");
                    bw.newLine();
                    bw.flush();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } 
            e.printStackTrace();
        }finally {
            if( null != s) { 
                try {
                    s.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
    }
    
   

}
package day.by.day.shangchuantupian.test;
//执行代码
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Test {

    public static void main(String[] args) {
        //创建seversocket对象链接端口号
        try {
            ServerSocket ss = new ServerSocket(8888);
            while( true) { 
                //接收客户端信息
                Socket s = ss.accept();
                //调用多线程
                new Thread(new SeverSocker(s)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

}

结束语:经得住诱惑,耐得住寂寞。

以上是关于java基础增强:网络编程TcpUdp案例的主要内容,如果未能解决你的问题,请参考以下文章

java中进行socket编程实现tcpudp协议总结

Java基础增强:集合的嵌套案例

网络基础TCPUDP协议

JavaWeb之Java基础知识增强

JavaWeb之Java基础知识增强

JavaWeb之Java基础知识增强