您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)怎么在Android中使用Websocket實(shí)現(xiàn)一個(gè)聊天室,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
WebSocket有以下幾個(gè)特點(diǎn)
1.支持 WebSocket RFC6455, Draft Hybi-10+ and WAMP v1
2.支持Android 2.2以上
3.非常好的兼容性
4.高性能的異步設(shè)計(jì)
5.非常容易使用的api
6.與Android app非常好的結(jié)合
7.沒有網(wǎng)絡(luò)操作在UI線程
8.開源
下面是官網(wǎng)給的一段示例代碼
private final WebSocketConnection mConnection = new WebSocketConnection(); private void start() { final String wsuri = "ws://localhost:9000"; try { mConnection.connect(wsuri, new WebSocketHandler() { @Override public void onOpen() { Log.d(TAG, "Status: Connected to " + wsuri); mConnection.sendTextMessage("Hello, world!"); } @Override public void onTextMessage(String payload) { Log.d(TAG, "Got echo: " + payload); } @Override public void onClose(int code, String reason) { Log.d(TAG, "Connection lost."); } }); } catch (WebSocketException e) { Log.d(TAG, e.toString()); } }
是不是挺簡(jiǎn)單的,在onOpen()方法中做與服務(wù)器連接的操作,onTextMessage()是收到服務(wù)器發(fā)送給客服端的消息,onClose()是與服務(wù)器斷開走的方法,發(fā)送消息用sendTextMessage()。
我是在MsgService 實(shí)現(xiàn)與服務(wù)器的連接與發(fā)送消息的,直接上代碼:
public class MsgService extends Service { private final IBinder binder = new MsgBinder(); private boolean flag = false; private WebSocketConnection mConnection; private Intent intent = new Intent("com.example.communication.RECEIVER"); public void startSocket(String sn) { final String wsuri = "ws://localhost:9000"; final JSONObject json = new JSONObject(); try { json.put("type", "command"); json.put("command", "auth"); json.put("key", Constants.API_KEY); json.put("access_token", UserManager.getInstance().getUser() .getUserAccessToken()); json.put("user_token", UserManager.getInstance().getUser() .getLYUserToken()); json.put("sn", sn); } catch (Exception e) { e.printStackTrace(); } try { mConnection.connect(wsuri, new WebSocketHandler() { @Override public void onOpen() { if (!flag) { //與服務(wù)器連接認(rèn)證 mConnection.sendTextMessage(json.toString()); } else { } } @Override public void onTextMessage(String payload) { intent.putExtra("message", payload); sendBroadcast(intent);//發(fā)送廣播給Fragment } @Override public void onClose(int code, String reason) { //連接失敗也把效應(yīng)的提示信息告訴用戶 Map<String, String> map = new HashMap<>(); map.put("status", "failed"); map.put("type", "command"); map.put("command", "auth"); String msg = map.toString(); intent.putExtra("message", msg); sendBroadcast(intent); } }); } catch (WebSocketException e) { e.printStackTrace(); } } //發(fā)送消息的方法 public void sendMessage(String message) { mConnection.sendTextMessage(message); } @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() { mConnection = new WebSocketConnection(); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } public class MsgBinder extends Binder { /** * 獲取當(dāng)前Service的實(shí)例 * * @return */ public MsgService getService() { return MsgService.this; } } @Override public void onDestroy() { super.onDestroy(); mConnection.disconnect(); } }
下面是Fragment的代碼
public class ChatRoomFragment extends Fragment { private View view, rootView, headView; private MsgService msgService; private UListView chatlist;//因?yàn)镾crollVie與ListView有沖突,重寫了ListView private static List<ChatMessage> mlist; private ChatMessage chatMessage; private ChatMessageAdapter chatMessageAdapter; private ScrollView scrollView; private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: msgService .startSocket(((PlayActivity) getActivity()).getSn()); break; default: break; } } }; //通過聊天室來更新在線人數(shù) public interface UpdataOnlineUsersListener { public void updataOnlineUser(int number); } private UpdataOnlineUsersListener mCallback; private EditText messageEditText; private Button sendBtn; private Intent mIntent; private MsgReceiver msgReceiver; private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Log.d("time", "msg"); } @Override public void onServiceConnected(ComponentName name, IBinder service) { // 返回一個(gè)MsgService對(duì)象 MsgService.MsgBinder binder = (MsgService.MsgBinder) service; if (binder != null) { Log.d("time", "msg"); } msgService = binder.getService(); if (msgService != null) { Log.d("time", "msg"); Message msg = new Message(); msg.what = 1; handler.sendMessage(msg); } } }; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_chat_room, container, false); return view; } public void bindChatService() { getActivity().bindService(mIntent, conn, Context.BIND_AUTO_CREATE); } public void destoryChatService() { getActivity().unbindService(conn); } @Override public void onAttach(Activity activity) { super.onAttach(activity); mCallback = (UpdataOnlineUsersListener) (activity); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // 動(dòng)態(tài)注冊(cè)廣播接收器 msgReceiver = new MsgReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.example.communication.RECEIVER"); getActivity().registerReceiver(msgReceiver, intentFilter); mIntent = new Intent(getActivity(), MsgService.class); bindChatService(); chatlist = (UListView) view.findViewById(R.id.chatlist); messageEditText = (EditText) view.findViewById(R.id.input); scrollView = (ScrollView) view.findViewById(R.id.scroll); scrollView.setFocusable(false); mlist = new ArrayList<ChatMessage>(); chatMessageAdapter = new ChatMessageAdapter(mlist, getActivity()); chatlist.setAdapter(chatMessageAdapter); chatlist.setVerticalScrollBarEnabled(true); sendBtn = (Button) view.findViewById(R.id.send); builder = new AlertDialog.Builder(getActivity()); sendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final View view = v; if (UserManager.getInstance().getUser().getGuest()) { ToastUtil.getInstance().showToast(getActivity(), getResources().getString(R.string.is_not_login)); } else { String message = messageEditText.getText().toString(); if (!message.equals("")) { JSONObject json = new JSONObject(); try { json.put("type", "message"); json.put("to", ""); json.put("message", message); } catch (Exception e) { } msgService.sendMessage(json.toString()); } else { Toast.makeText(getActivity(), getResources().getString(R.string.textisnull), Toast.LENGTH_SHORT).show(); } } HideKeyboard(v); messageEditText.setText(""); } }); rootView = (View) view.findViewById(R.id.rootview); rootView.setFocusable(true); rootView.setFocusableInTouchMode(true); rootView.requestFocus(); setRetainInstance(true); } //隱藏軟鍵盤 private void HideKeyboard(View v) { InputMethodManager imm = (InputMethodManager) v.getContext() .getSystemService(Context.INPUT_METHOD_SERVICE); if (imm.isActive()) { imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0); } } @Override public void onResume() { super.onResume(); scrollView.smoothScrollTo(0, 0); } //接受服務(wù)端發(fā)送的消息 public class MsgReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String msg = intent.getStringExtra("message"); try { JSONObject json = new JSONObject(msg); if (json.getString("type").equals("command")) { String command = json.getString("command"); if (command.equals("auth")) { { chatMessage = new ChatMessage("tips", "服務(wù)器連接中...", "111", "111"); mlist.add(chatMessage); chatMessageAdapter.notifyDataSetChanged(); } if (json.getString("status").equals("success")) { chatMessage = new ChatMessage("tips", "服務(wù)器連接中成功", "111", "111"); } else { chatMessage = new ChatMessage("tips", "服務(wù)器連接中失敗", "111", "111"); } mlist.add(chatMessage); chatMessageAdapter.notifyDataSetChanged(); } else if (command.equals("online_status")) { int onlineUser = json.getInt("online"); mCallback.updataOnlineUser(onlineUser); } } else if (json.getString("type").equals("message")) { chatMessage = new ChatMessage(json.getString("type"), json.getString("from"), json.getString("content"), json.getString("time")); mlist.add(chatMessage); chatMessageAdapter.notifyDataSetChanged(); } Log.d("time", mlist.toString()); } catch (JSONException e) { e.printStackTrace(); } chatlist.setSelection(chatMessageAdapter.getCount());//讓ListView滑到最下面 } } @Override public void onDestroy() { // 停止服務(wù) getActivity().unbindService(conn); // 注銷廣播 getActivity().unregisterReceiver(msgReceiver); super.onDestroy(); } }
上述就是小編為大家分享的怎么在Android中使用Websocket實(shí)現(xiàn)一個(gè)聊天室了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。