利用Socket实现android通讯(上)

一.服务器端

1.添加服务器 要用的jar包

2.连接数据库

新建conn.java

public class conn {

public static Connection isConn() {
        Connection con = null;
          try {
              // 获得MySQL驱动的实例
              Class.forName("com.mysql.jdbc.Driver").newInstance();
              // 获得连接对象(提供:地址,用户名,密码)
              con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root", "123456");
             
              if (!con.isClosed())
                System.out.println("Successfully connected ");
              else
                System.out.println("failed connected");
          }catch (Exception e) {
                  e.printStackTrace();
          
          }
        return con;
    }

}

3.新建继承Thread的类,用于客服端的多次请求

public class ServiceThread extends Thread{
    Socket socket=null;
    InputStream in;
    InputStreamReader reader;
    BufferedReader br;
    boolean fagle=false;
    String type=null;

    
     public ServiceThread(Socket socket) {
        // TODO Auto-generated constructor stub
         this.socket=socket;
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        try {
//            输入流
             in=socket.getInputStream();
             reader=new InputStreamReader(in,"utf-8");
             br=new BufferedReader(reader);
            String info=null;
            String user=null;
            StringBuffer buff=new StringBuffer();
            String select=null;
            while ((info=br.readLine())!=null) {
                System.out.print("客服端说:"+info);
//                HashMap<String, String> param=info;
//                buff.append(info+",");
//                System.out.print(buff);
//            Log.e
            
                Map<String, String> tranMap = mapStringToMap(info);
                 type=tranMap.get("type");
                if(type.equals("login")) {
                       System.out.println("\nusername:"+tranMap.get("username"));
                        System.out.println("\npassword:"+tranMap.get("password"));
//                        System.out.println("c:"+tranMap.get("c"));
                        fagle= DataTest.isLoginSucc(tranMap.get("username"), tranMap.get("password"));
                }else if (type.equals("sendInfo")) {
                    fagle=     DataTest.isSendMSg(tranMap.get("username"),tranMap.get("content"));

                }else if(type.equals("showInfo")) {
//                    查询
                     select=DataTest.ShowMsg(tranMap.get("username"));
                }
                 
            }
            socket.shutdownInput();
//            4.获取输入流
            OutputStream os=socket.getOutputStream();
            PrintWriter pw=new PrintWriter(os);
            if(type.equals("login")||type.equals("sendInfo")) {
                if(fagle) {
                    pw.write("success");
                }else {
                    pw.write("fail");

                }
            }else  if (type.equals("showInfo")){
                pw.write(select);
                
            }
            
//            pw.write("密码错误");
            pw.flush();
        
        }catch (Exception e) {
            // TODO: handle exception
        }finally {
            //            5.关闭资源
            try {
                if(br!=null) {
                    br.close();
                }
                if(br!=null) {
                    in.close();
                }
                if(reader!=null) {
                    reader.close();
                }
                if(socket!=null) {
                    socket.close();
                }
            }catch (IOException e) {
                // TODO: handle exception
            }
            
            
        }
    }
    private static Map<String, String> mapStringToMap(String str) {
        str = str.substring(1, str.length() - 1);
        String[] strs = str.split(",");
        Map<String, String> map = new HashMap<String, String>();
        for (String string : strs) {
            String key = string.split("=")[0].trim();
            String value = string.split("=")[1];
            map.put(key, value);
        }
        return map;
    }

}

4.DataTest类

public class DataTest {
//    判断登录
       public static boolean isLoginSucc(String username,String password) {
            Connection con = null;
            Statement st = null;
            ResultSet rs = null;
            PreparedStatement sm;
            boolean fagle=false;
           try {
               
               con=conn.isConn();
               
                  System.out.println("用户名:"+username);
                  String sql="select count(0) count from tb_user where username=? and password=?";
                   sm=con.prepareStatement(sql);
                   sm.setString(1, username);
                   sm.setString(2, password);

                   rs = sm.executeQuery();
                  while (rs.next()) {
//                    System.out.println("id:"+rs.getInt(1)+"\n username:"+rs.getString(2)+"\n password:"+rs.getString(3));
                      int id=rs.getInt(1);
                    if(id>0) {
                        System.out.println("存在");
                        fagle= true;
                        
                    }else {
                        System.out.println("不存在");
                        fagle= false;
                    }
                }
                  
                  
                  // 关闭链接
                  con.close();
                } catch(Exception e) {
                  System.err.println("Exception: " + e.getMessage());
                }
           return fagle;
       }
//发送消息
       public static boolean isSendMSg(String username,String content) {
           Connection con = null;
            Statement st = null;
            ResultSet rs = null;
            PreparedStatement sm;
            boolean fagle=false;
           try {
                  // 获得MySQL驱动的实例
                  Class.forName("com.mysql.jdbc.Driver").newInstance();
                  // 获得连接对象(提供:地址,用户名,密码)
                  con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root", "123456");
                 
                  if (!con.isClosed()) {
                        System.out.println("Successfully connected ");
                        String sql="insert into tb_send(username1,content,head)  value(?,?,?)";
                        sm=con.prepareStatement(sql);
                           sm.setString(1, username);
                           sm.setString(2, content);
                           sm.setString(3, "123456");
//                           rs = sm.executeQuery();
                           int num = sm.executeUpdate();
                            if(num>0){
                                fagle=true;
                                System.out.println("插入成功!!");
                            }else {
                                fagle=false;
                            }
                        
                  }else {
                      fagle=false;
                        System.out.println("failed connected");

                  }
                  
           }catch (Exception e) {
            // TODO: handle exception
               System.out.println(e.getMessage());
        }
           return fagle;
       }
//查看消息
       public static String ShowMsg(String username) {
            Connection con = null;
            Statement st = null;
            ResultSet rs = null;
            PreparedStatement sm;
            boolean fagle=false;
            String msg=null;
            JSONObject object=new JSONObject();
            JSONArray array=new JSONArray();
           try {
                  // 获得MySQL驱动的实例
                  Class.forName("com.mysql.jdbc.Driver").newInstance();
                  // 获得连接对象(提供:地址,用户名,密码)
                  con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root", "123456");
                 
                  if (!con.isClosed())
                    System.out.println("Successfully connected ");
                  else
                    System.out.println("failed connected");
                   String sql="select * from tb_send where username1=?;";
                   sm=con.prepareStatement(sql);
                   sm.setString(1, username);
                  //建立一个Statement,数据库对象
//                  st = con.createStatement();
//                   运行SQL查询语句
                  rs = sm.executeQuery();
                  // 读取结果集
                  while (rs.next()) {
                      object.put("username", rs.getString(2));
                      object.put("content", rs.getString(3));
                      array.add(object);
//                       msg=rs.getString(3);
//                    System.out.println("column1:"+rs.getInt(1));
//                    System.out.println("column2:"+rs.getString(2));
//                    System.out.println("column3:"+rs.getString(3));
//                    System.out.println("column4:"+rs.getString(4));
                  }
                  
           }catch (Exception e) {
            // TODO: handle exception
               System.out.println(e.getMessage());
        }
        
            return array.toString();
    
           
       }

}

5.创建socket实现通讯

public class Server {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //        创建服务器端的socket,绑定端口并监听
        Socket socket=null;
        int count=0;
        try {
            ServerSocket serverSocket=new ServerSocket(8888);
            //            利用accpte方法进行监听
            System.out.println("*****正在等客服端连接******");
             
             while (true) {
                 socket=serverSocket.accept();
                ServiceThread serThread=new ServiceThread(socket);
                serThread.start();
                count++;
                System.out.println(count+"\n");
            }
             
//            输入流
//            InputStream in=socket.getInputStream();
//            InputStreamReader reader=new InputStreamReader(in,"utf-8");
//            BufferedReader br=new BufferedReader(reader);
//            String info=null;
//            while ((info=br.readLine())!=null) {
//                System.out.print("客服端说"+info);
//                
//            }
//            socket.shutdownInput();
            4.获取输入流
//            OutputStream os=socket.getOutputStream();
//            PrintWriter pw=new PrintWriter(os);
//            pw.write("密码错误");
//            pw.flush();
//            //            5.关闭资源
//            br.close();
//            in.close();
//            reader.close();
//            socket.close();
            
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值