码迷,mamicode.com
首页 > 移动开发 > 详细

Android 聊天室(二)

时间:2015-04-28 14:03:43      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

在完成了使用socket进行简单的聊天室的开发之后,博主决定进行注册和登陆功能的开发。这也是为了在后期实现更多的功能时必不可少的一个工作。 注册和登录的大概流程如下:

1. 用xanpp软件搭建本地服务器,并新建数据库用于存放,注册用户的注册信息

2. 使用php语言编写App

3. 编写客户端代码,实现注册和登陆功能

接下来,我就按照这三大块儿进行详细的介绍:

  • 服务器和数据库的搭建 

     有关这部分的内容,在我以前的博客《ClientToServer》中有所介绍,在这里就不再重复介绍。 * App接口的实现 App的借口部分主要实现的是根据客户端的请求对数据库进行相应的操作:接收到“注册”请求时,首先查询数据库中是否已经存在此用户,如果存在则返回“exist”给客户端,告知“此用户名已被占用,请重新输入”,如果不存在,则将此用户名和密码插入到数据库中,并返回“ok”表示“注册成功”,如果数据插入失败,则返回“error”表示“注册失败”。当接收到“登录”请求时,则在数据库中查找是否存在用户名&密码与客户端发过来的均一致的条目,如果存在,则返回“ok”表示“登录成功”,反之,返回“error”表示“登录失败”。注册的接口文件 login.php:

<?php
$conn = mysql_connect("localhost","root","");
if(!$conn){
    die("conn error");
}
$db = mysql_select_db("siguoyi", $conn);
mysql_set_charset(‘utf8‘);

$jsonString = $_POST["jsonString"];
$jsonString = str_replace(‘\"‘,‘"‘,$jsonString);
$obj=json_decode($jsonString);

$username = $obj->username;
$password = $obj->password;
$state = $obj->state;

$sql1 = "SELECT * FROM client WHERE (`username` = ‘$username‘)";
$resultNew1 = mysql_query($sql1, $conn);
if(mysql_num_rows($resultNew1) < 1){
try {
    $sql = "INSERT INTO `client`
    (`username`,`password`,`state`) VALUES (‘$username‘,‘$password‘,‘$state‘)";
    //echo $sql;
    $resultNew = mysql_query($sql, $conn);
    if (!$resultNew) {
        echo "error";
    }else{
        echo "ok";
    }
    $insert_id=mysql_insert_id();
} catch (Exception $e) {}
}else {
    echo "exist";
}
?>

登录的接口文件 sign.php:

<?php
$conn = mysql_connect("localhost","root","");
if(!$conn){
    die("conn error");
}
$db = mysql_select_db("siguoyi", $conn);
mysql_set_charset(‘utf8‘);

$jsonString = $_POST["jsonString"];
$jsonString = str_replace(‘\"‘,‘"‘,$jsonString);
$obj=json_decode($jsonString);

$username = $obj->username;
$password = $obj->password;


    $sql = "SELECT * FROM client WHERE (`username` = ‘$username‘ and `password` = ‘$password‘)";
    
    $resultNew = mysql_query($sql, $conn);
    
    if (mysql_num_rows($resultNew) < 1 ) {
        echo "error";
    }else{
        echo "ok";
    }
?>
  • 客户端功能实现
     客户端主要功能为获取用户注册或者登录时所输入的用户名及密码,并将信息通过json进行上传,并通过接收接口返回的信息来判断此次操作是否成功,然后进行之后的功能执行或者页面跳转。

注册模块的代码 Login.java

public class Login extends Activity{

    private static final String tag ="Login";
    private EditText et_username;
    private EditText et_password;
    private Button bt_login_confirm;
    private Button bt_login_cancel;
    private Handler mHandler;
    
    JSONObject jsonObject = new JSONObject();
    private String Url = "http://10.105.36.51/new/login.php";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
        bt_login_confirm = (Button) findViewById(R.id.bt_login_confirm);
        bt_login_cancel = (Button) findViewById(R.id.bt_login_cancel);
        
        mHandler = new Handler(){

            @Override
            public void handleMessage(Message msg) {
                    Log.v(tag, "handle msg: "+msg.obj);
                    String s = msg.obj.toString().trim();
                    char[] cc = s.toCharArray();
                    String sb ="";
                    for(int i = 1; i < cc.length; i++ ){
                        sb+=cc[i];
                    }
                    
                    Log.v(tag, sb+","+sb.hashCode()+","+"exist".hashCode());
                    if(sb.equals("ok")){
                        Toast.makeText(Login.this, "注册成功!", Toast.LENGTH_SHORT).show();
                        et_username.setText("");
                        et_password.setText("");
                        Login.this.finish();
                        Intent intent = new Intent(Login.this, SignIn.class);
                        startActivity(intent);
                    } else 
                        if(sb.equals("error")){
                            Toast.makeText(Login.this, "注册失败,请重试", Toast.LENGTH_SHORT).show();
                    } else 
                        if(sb.equals("exist")){
                            Log.v(tag, "此用户名已被占用,请重新输入");
                            Toast.makeText(Login.this, "此用户名已被占用,请重新输入", Toast.LENGTH_SHORT).show();
                    }
                }
            
            
        };
        
        bt_login_confirm.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                
                String username = et_username.getText().toString();
                String password = et_password.getText().toString();
                int state = 0;
                
                try {
                    jsonObject.put("username", username);
                    jsonObject.put("password", password);
                    jsonObject.put("state", state);
                    

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.v(tag, "json" + jsonObject);
                new Thread(){

                    @Override
                    public void run() {
                        Utils upload = new Utils(Url, jsonObject);
                        String result = upload.upData();
                        Log.v(tag, "result:" + result+","+result.hashCode());
                        
                        Message msg = new Message();
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                    
                }.start();    
            }
        });
        
        bt_login_cancel.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {                
                Login.this.finish();
            }
        });        
        
    }
}

 

登录模块的代码 SignIn.java

public class SignIn extends Activity{

    private static final String tag = "SignIn";
    
    private EditText et_username_sign;
    private EditText et_password_sign;
    private Button bt_sign_confirm;
    private Button bt_sign_cancel;
    
    private Handler mHandler;
    
    JSONObject jsonObject = new JSONObject();
    private String Url = "http://10.105.36.51/new/sign.php";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signin_layout);
        
        et_username_sign = (EditText) findViewById(R.id.et_sign_username);
        et_password_sign = (EditText) findViewById(R.id.et_sign_password);
        bt_sign_confirm  = (Button) findViewById(R.id.bt_sign_confirm);
        bt_sign_cancel = (Button) findViewById(R.id.bt_sign_cancel);
        
        mHandler = new Handler(){

            @Override
            public void handleMessage(Message msg) {
                    Log.v(tag, "handle msg: "+msg.obj);
                    String s = msg.obj.toString().trim();
                    char[] cc = s.toCharArray();
                    String sb ="";
                    for(int i = 1; i < cc.length; i++ ){
                        sb+=cc[i];
                    }
                    
                    Log.v(tag, sb+","+sb.hashCode()+","+"exist".hashCode());
                    if(sb.equals("ok")){
                        Toast.makeText(SignIn.this, "登录成功!", Toast.LENGTH_SHORT).show();
                        et_username_sign.setText("");
                        et_password_sign.setText("");
                        SignIn.this.finish();
                        
                    } else 
                        if(sb.equals("error")){
                            Toast.makeText(SignIn.this, "登录失败,请重试", Toast.LENGTH_SHORT).show();
                    } 
                }
            
            
        };
        
        bt_sign_confirm.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                String username = et_username_sign.getText().toString();
                String password = et_password_sign.getText().toString();
                
                try {
                    jsonObject.put("username", username);
                    jsonObject.put("password", password);
                    

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.v(tag, "json" + jsonObject);
                new Thread(){

                    @Override
                    public void run() {
                        Utils upload = new Utils(Url, jsonObject);
                        String result = upload.upData();
                        Log.v(tag, "result:" + result);
                        
                        Message msg = new Message();
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                    
                }.start();    
                
            }
        });
        
        bt_sign_cancel.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                SignIn.this.finish();
            }
        });
    }
    
}

 

网络模块的代码 Utils.java

public class Utils {
    
    private static final String tag = "Utils";
    private String uploadDataURL = null;
    private String jsonObject;

    public Utils(String uploadDataURL, JSONObject jsonObject) {
        this.uploadDataURL = uploadDataURL;
        this.jsonObject = jsonObject.toString();
    }

    public Utils(String uploadDataURL, String jsonObject) {
        this.uploadDataURL = uploadDataURL;
        this.jsonObject = jsonObject;

    }

    public String upData() {
        String resultID = "-1";
        

        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
        nameValuePair.add(new BasicNameValuePair("jsonString", jsonObject));
        InputStream inputStream = null;

        try {
            HttpClient httpClient = new DefaultHttpClient();
            
            HttpPost httpPost = new HttpPost(uploadDataURL);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            
            inputStream = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            String result = "";
            if((line = reader.readLine()) != null){
                
                resultID = line;
                Log.v(tag, resultID);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultID;
    }
}

Android 聊天室(二)

标签:

原文地址:http://www.cnblogs.com/siguoyi/p/4462733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!