以Android端为客户端,servlet端为服务端的实时通讯——基础

  • Post author:
  • Post category:其他


最近因为学弟项目需求 要做实时通讯,想让我研究研究,我就帮忙写了写,怎么说呢,收获也是有的吧,然后打算把整个通讯给大家展示一遍,包括服务端和客户端,有兴趣的可以关注小编

源码下载地址:

http://download.csdn.net/download/gywuhengy/9873080


先说整个项目的功能和过程

1.先实现两端交互

2.可以注册,登录用户

3.可以相互加好友

4.可以相互发文字

5.可以相互发送表情,语音等

本编博客主要来完成第一个内容:

一、先说Android端的实现:

1、注册页面

public class RegisterActivity extends AppCompatActivity {
    private EditText et_register_user, et_register_pwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        inItUI();
    }

    //初始化UI
    private void inItUI() {
        et_register_user = (EditText) findViewById(R.id.et_register_user);
        et_register_pwd = (EditText) findViewById(R.id.et_register_pwd);
    }

    //提交注册数据
    public void click_Register_push(View view) {
        String user = et_register_user.getText().toString();
        String pwd = et_register_pwd.getText().toString();
        //向服务器发送数据
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(KeyValue.USER, user);
            jsonObject.put(KeyValue.PWD, pwd);
            register(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void register (final JSONObject jsO){
        RequestMethod.RequestLogin(this,jsO, new MyInterface.onRegisterCallback() {
            @Override
            public void Success(String role) {
            }
            @Override
            public void Fail(String error) {

            }
            @Override
            public void UnkownError(String unkownerror) {
            }
        });
    }
}

2、登录请求类:


public class RequestMethod {
    //登录请求方法
    public static  void  RequestLogin(final Activity activity, final JSONObject jsonObject,final MyInterface.onRegisterCallback onRegisterCallback){

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                JSONObject resultObject = ResponseMethod.sendRegister(jsonObject, UrlString.REGISTER);
                Log.e("gaoyu", "返回结果是:" + resultObject.toString());
                //解析登录结果
            }
        }).start();
    }
}

3、网络处理类:

public class ResponseMethod {
    //服务端返回值方法
    public static JSONObject sendRegister(JSONObject jo2, String url) {
        InputStreamReader isr = null;
        DataOutputStream dos = null;
        HttpURLConnection urlConn = null;
        BufferedReader bufferedReader = null;
        JSONObject jsonObject = null;
        try {
            URL url1 = new URL(url);
            urlConn = (HttpURLConnection) url1.openConnection();
            urlConn.setDoInput(true);//设置输入流采用字节流
            urlConn.setDoOutput(true);//设置输出流采用字节流
            urlConn.setRequestMethod("POST");//post方法
            urlConn.setUseCaches(false);//缓存
            urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置meta参数
            urlConn.setRequestProperty("Charset", "utf-8");//缓存
            urlConn.connect();//连接服务器发送消息
            Log.e("gaoyu", "发送的信息是" + jo2.toString());
            dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write((jo2.toString()).getBytes());//写数据
            dos.close();
            dos.flush();
            isr = new InputStreamReader(urlConn.getInputStream());
            bufferedReader = new BufferedReader(isr);
            String result = "";
            String readLine = null;
            while ((readLine = bufferedReader.readLine()) != null) {
                result += readLine;
            }
            Log.e("gaoyu", "返回的" + result);
            result = removeBOM(result);
            jsonObject = new JSONObject(result);
            bufferedReader.close();
            isr.close();
            urlConn.disconnect();//关闭连接
            return jsonObject;
        } catch (MalformedURLException e) {
            Log.e("gaoyu", "异常=MalformedURLException");
            e.printStackTrace();
            return jsonObject;
        } catch (IOException e) {
            Log.e("gaoyu", "异常=IOException");
            e.printStackTrace();
            return jsonObject;
        } catch (JSONException e) {
            Log.e("gaoyu", "异常=JSONException");
            e.printStackTrace();
            return jsonObject;
        }
    }


    public static final String removeBOM(String data) {
        if (TextUtils.isEmpty(data)) {
            return data;
        }
        if (data.startsWith("\ufeff")) {
            return data.substring(1);
        } else {
            return data;
        }
    }
}

二、再说服务端的实现(较简单):

1、servlet的处理

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    public RegisterServlet() {
        super();
    }

    public void destroy() {
        super.destroy();
    }

    /**
     * 处理get请求 request用于获得客户端信息 response用于向客户端返回信息
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 可以将逻辑放在doPost里面
        this.doPost(request, response);
    }

    /**
     * 逻辑处理
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 解决中文乱码
        request.setCharacterEncoding("UTF-8");
        //response.setCharacterEncoding("gbk");
        response.setContentType("text/html;charset=UTF-8");
        //response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        // 获取客户端数据
        BufferedReader in = new BufferedReader(new InputStreamReader(
                request.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;
        String result = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        result = sb.toString();
        System.out.println("接受数据是" + result);
        //开始返回数据
        Map params = new HashMap();
        params.put("status", "success");
        JSONObject jsonObject = JSONObject.fromObject(params);
        out.write(jsonObject.toString());
        out.flush();
        out.close();

    }

    public void init() throws ServletException {
        // Put your code here
    }

}

最后我们来看一下实现效果:

android端

这里写图片描述

点击注册以后 服务端日志 :

这里写图片描述

Android接受服务端返回值日志:

这里写图片描述

这样就实现的 android和服务端的交互!

小编会尽快更新以后功能,敬请期待!



版权声明:本文为gywuhengy原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。