• Socket通信综合示例


    1用户注册
    客户单选择‘用户注册’,提示要输入用户名,密码,确认密码,校验成功后将用户
    信息保存到数据库,并提示数据库注册成功,请登录
    2用户登录
    客户端选择‘登录以后’后,提示输入用户名和密码,验证成功则提示上传文件
    ,验证失败则给出提示信息,并可以重新登录
    3文件上传
    客户端输入上传文件的路径,并读取文件数据,通过输出流发送到服务端,服务端接受
    后将上传文件保持在数据库

    package com.slp.entity;
    
    import java.io.Serializable;
    
    public class File implements  Serializable {
    
        /**
         * 
         */
        private static final long serialVersionUID = 1254554707571682105L;
        private int fid;
        private String fname;
        private byte[] focntent;
        public int getFid() {
            return fid;
        }
        public void setFid(int fid) {
            this.fid = fid;
        }
        public String getFname() {
            return fname;
        }
        public void setFname(String fname) {
            this.fname = fname;
        }
        public byte[] getFocntent() {
            return focntent;
        }
        public void setFocntent(byte[] focntent) {
            this.focntent = focntent;
        }
        public File(int fid, String fname, byte[] focntent) {
            this.fid = fid;
            this.fname = fname;
            this.focntent = focntent;
        }
        public File(String fname,byte[] focntent){
            this.fname=fname;
            this.focntent=focntent;
        }
        
    }
    package com.slp.entity;
    
    import java.io.Serializable;
    
    public class Users implements  Serializable{
    
        /**
         * 
         */
        private static final long serialVersionUID = -7751437846681691870L;
        private int id;
        private String username;
        private String password;
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public Users(int id, String username, String password) {
            super();
            this.id = id;
            this.username = username;
            this.password = password;
        }
        public Users(){
            
        }
        
    }
    package com.slp.service;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import com.imooc.entity.File;
    import com.imooc.util.Util;
    
    public class FileService {
        private Connection conn = null;
        private PreparedStatement ptmt = null;
        private ResultSet rs = null;
    
        public void savefile(File file) {
            String sql = (" insert into tb_file(fname,focntent) values(?,?)");
            try
            {   conn=Util.getConnection();
                ptmt = conn.prepareStatement(sql);
                ptmt.setString(1, file.getFname());
                ptmt.setBytes(2, file.getFocntent());
                ptmt.executeUpdate();
            } catch (
    
            SQLException e)
            { 
                e.printStackTrace();
            } finally{
                Util.closeAll(conn, ptmt, rs);
            }
        }
    
    }
    package com.slp.service;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import com.imooc.entity.Users;
    import com.imooc.util.Util;
    
    public class UsersService {
        private PreparedStatement ptmt = null;
        private ResultSet rs = null;
        private Connection conn=null;
        public void zhuce(Users users) {
            String sql = "insert into tb_user(username,password) values(?,?)";
            try {
                conn=Util.getConnection();
                ptmt = conn.prepareStatement(sql);
                ptmt.setString(1, users.getUsername());
                ptmt.setString(2, users.getPassword());
                ptmt.execute();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                Util.closeAll(conn, ptmt, rs);
            }
        }
    
        public Boolean Denglu(Users users){
            String sql = "Select  username,password from tb_user where username=? and password=? ";
            try {
                
                conn = Util.getConnection();
                ptmt = conn.prepareStatement(sql);
                ptmt.setString(1, users.getUsername());
                ptmt.setString(2, users.getPassword());
                rs = ptmt.executeQuery();
                if (rs.next()) {
                    return true;
                } 
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                Util.closeAll(conn, ptmt, rs);
            }
            return false;
        }
    
    }
    package com.slp.socket;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
    
    import com.imooc.entity.File;
    import com.imooc.entity.Users;
    import com.imooc.service.FileService;
    import com.imooc.service.UsersService;
    import com.imooc.util.CommendTranser;
    
    public class SocketClient {
        Scanner scan = new Scanner(System.in);
        private Socket socket = null;
        // Socket ss = new Socket("localhost", 1346);
        // Scanner scan = new Scanner(System.in);
        // String in = scan.next();
        // InputStream is = ss.getInputStream();
        // InputStreamReader isr = new InputStreamReader(is);
        // BufferedReader bfr=new BufferedReader(isr);
        // String info;
        // while((info=bfr.readLine())!=null){
        // System.out.println("我是客户端 "+"	"+"服务器说"+info);
        // }
        //
        //
        // OutputStream os = ss.getOutputStream();
        // PrintWriter pw = new PrintWriter(os);
        // pw.write(in);
    
        public void showMainMenu() {
            System.out.println("******欢迎使用imooc上传器*******");
            System.out.println("1 用户登录  ,2 用户注册 ,3 退出");
            System.out.println("***************************");
            System.out.println("请选择:》》》》》》》》");
            int choose = scan.nextInt();
            switch (choose) {
            case 1:
                showlogin();
                break;
            case 2:
                showzhuce();
                break;
            case 3:
                System.out.println("再见了,你炸了");
                System.exit(0);
            default:
                System.out.println(" 输入有误");
                System.exit(0);
            }
        }
    
        public void showlogin() {
            Users users = new Users();
            System.out.println("欢迎使用登录");
            CommendTranser transer = new CommendTranser();
            int count = 0;
            while (true) {
                if (count >= 3) {
                    System.out.println("您已经三次输入失败,再见");
                    System.exit(0);
                }
                System.out.println("请输入用户名");
                users.setUsername(scan.next());
                System.out.println("请输入密码");
                users.setPassword(scan.next());
                transer.setCmd("login");
                transer.setData(users);
                count++;
                try {
                    socket = new Socket("localhost", 1346);
                    sendData(transer); 
                    transer=getDate();
                    System.out.println("   " + transer.getResult());
                    System.out.println("***********************");
                    if (transer.isFlag()) {
                        break;
                    }
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    clossAll();
                }
    
            }
            showUploadFile();
    
        }
    
        public void showzhuce() {
            Users users = new Users();
            System.out.println("欢迎使用注册");
            CommendTranser transer = new CommendTranser();
            while (true) {
                System.out.println("请输入用户名");
                users.setUsername(scan.next());
                System.out.println(" 请输入密码");
                users.setPassword(scan.next());
                System.out.println("请再次输入密码");
                String rePassword = scan.next();
                if (!users.getPassword().equals(rePassword)) {
                    System.out.println("俩次输入不一致");
                    System.out.println("**************");
                    continue;
                }
                transer.setCmd("zhuce");
                transer.setData(users);
                try {
                    socket = new Socket("localhost", 1346);
                    sendData(transer); 
                    transer=getDate();
                    System.out.println("  " + transer.getResult());
                    System.out.println("***********************");
                    if (transer.isFlag()) {
                        break;
                    }
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    clossAll();
                }
            }
            showUploadFile();
        }
    
        public void showUploadFile() {
            System.out.println("请输入上传的绝对路径 如: (e://imooc//dog.jpg)");
            String path = scan.next();
    
            File file = null;
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            String fname = path.substring(path.lastIndexOf("/") + 1);
            try {
                fis = new FileInputStream(path);
                byte[] focntent = new byte[fis.available()];
                bis = new BufferedInputStream(fis);
                bis.read(focntent);
                file = new File(fname, focntent);
    
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            CommendTranser transer = new CommendTranser();
            transer.setCmd("uploadFile");
            transer.setData(file);
            try {
                socket = new Socket("localhost", 1346);
                sendData(transer); 
                transer=getDate();
                System.out.println(transer.getResult());
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                clossAll();
            }
        }
    
    
        public CommendTranser sendData(CommendTranser transer) {
            ObjectOutputStream oos=null;//对象输出流
                try {
                 oos=new ObjectOutputStream(socket.getOutputStream());
                 oos.writeObject(transer);
                  return transer;
                } catch (IOException e) {
                    e.printStackTrace();
                } 
        return null;
        }
        
        
        public CommendTranser  getDate(){
            ObjectInputStream ois =null;//对象输入流
            CommendTranser transer = null;
             try {
                ois=new ObjectInputStream(socket.getInputStream());
                transer= (CommendTranser) ois.readObject();
            } catch (IOException e) {
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return transer;
        }
    
        public void clossAll() {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    package com.slp.socket;
    
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Scanner;
    
    public class SocketServer {
    
        
        public static void main(String[] args) {
        try {
            ServerSocket serversocket=new ServerSocket(1346);
            Socket socket=null;
            System.out.println("");
            while(true){
                 socket=serversocket.accept();
                System.out.println("欢迎您..");
                SocketThread thread=new SocketThread(socket);
                thread.start();
                
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        
    }
    }
    package com.slp.socket;
    
    public class SocketStart {
    
        public static void main(String[] args) {
    
            SocketClient client=new SocketClient();
            client.showMainMenu();
    }
    }
    package com.slp.socket;
    
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.net.Socket;
    
    import com.imooc.entity.File;
    import com.imooc.entity.Users;
    import com.imooc.service.FileService;
    import com.imooc.service.UsersService;
    import com.imooc.util.CommendTranser;
    
    public class SocketThread  extends Thread{
    
        private Socket socket=null;
        private ObjectInputStream ois =null;//对象输入流
        private ObjectOutputStream oos=null;//对象输出流
        private UsersService us=new UsersService();//用户业务对象
        private FileService fs=new FileService();//文件业务对象
        //通过构造方法,初始化socket
        public SocketThread (Socket socket){
            this.socket=socket;
        }
        @Override
        public void run() {
            try {
                ois=new ObjectInputStream(socket.getInputStream());
                oos=new ObjectOutputStream(socket.getOutputStream());
                CommendTranser transer=(CommendTranser)ois.readObject();
                transer=execute(transer);
                oos.writeObject(transer);
                 
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
             public CommendTranser execute(CommendTranser transer){
                 String cmd =transer.getCmd();
                 if(cmd.equals("login")){
                     Users users=(Users)transer.getData();
                     boolean flag=us.Denglu(users);
                       transer.setFlag(flag);
                       if(flag){
                           transer.setResult("登录成功");
                       }else{
                           transer.setResult("用户名或密码不正确");
                       }
                 }else if(cmd.equals("zhuce")){
                     Users users=(Users)transer.getData();
                     us.zhuce(users);
                     boolean flag= us.Denglu(users);
                     transer.setFlag(flag);
                     if(flag){
                         transer.setResult("注册成功");
                     }else{
                         transer.setResult("注册失败,未知原因");
                     
                     }     
                     }else if(cmd.equals("uploadFile")){
                     File file=(File)transer.getData();
                     fs.savefile(file);
                     transer.setResult(" 上传成功");            
                     }
                 return transer;
             }
             
    }
    package com.slp.util;
    
    import java.io.Serializable;
    
    public class CommendTranser implements  Serializable {
        private static final long serialVersionUID = 1L;
        private String cmd;//当前操作的命令
        private Object data;//发送的数据
        private boolean flag;//操作是否成功
        private String result;//返回的结果
        public String getCmd() {
            return cmd;
        }
        public void setCmd(String cmd) {
            this.cmd = cmd;
        }
        public Object getData() {
            return data;
        }
        public void setData(Object data) {
            this.data = data;
        }
        public boolean isFlag() {
            return flag;
        }
        public void setFlag(boolean flag) {
            this.flag = flag;
        }
        public String getResult() {
            return result;
        }
        public void setResult(String result) {
            this.result = result;
        }
    
    
    }
    package com.slp.util;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    //注:我是将原来的引用Util util=new Util();
       
    public class Util {
    //    private static final String URL = "jdbc:mysql://127.0.0.1:3306/imooc";
    //    private static final String NAME = "root";
    //    private static final String PASSWORD = "199666";
    //
    //    public static Connection conn=null;
    //
    //    static{
    //    // 获得数据库的连接
    //    try {
    //        Class.forName("com.mysql.jdbc.Driver");
    //        conn = DriverManager.getConnection(URL, NAME, PASSWORD);
    //    } catch (SQLException e) {
    //        e.printStackTrace();
    //    } catch (ClassNotFoundException e) {
    //        e.printStackTrace();
    //    }
    //    }
        
    //    public  Connection getConnection(){
    //    
    //    
    //    return conn;
    //}
    
        public static  Connection getConnection(){
             String driverClassName="com.mysql.jdbc.Driver";
            String URL = "jdbc:mysql://127.0.0.1:3306/imooc";
           String username = "root";
            String password = "199666";
            Connection conn=null;
            try {
                Class.forName(driverClassName);
                conn=DriverManager.getConnection(URL, username, password);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return conn;
        }
    
    //    关闭资源的操作
        public static  void closeAll( Connection conn,Statement stmt,ResultSet rs){
            
            try {
                if(conn!=null){
                    conn.close();
                }
                if(stmt!=null){
                    stmt.close();
                }if(rs!=null){
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            
        }
        
        
        
    }
  • 相关阅读:
    How to Install Tomcat
    使用Application_Error捕获站点错误并写日志
    安装 SQL Server2008 安装程序规则支持提示“重新启动计算机”失败
    历史执行Sql语句性能分析 CPU资源占用时间分析
    返回List的分页方法
    @@IDENTITY与SCOPE_IDENTITY()
    Debugging Failed Because Integrated Windows Authentication Is Not Enabled
    一般经验总结
    dom中实现全选复选框的实例。
    dom中表格的修改 增加行例
  • 原文地址:https://www.cnblogs.com/dream-to-pku/p/6127396.html
Copyright © 2020-2023  润新知