轉載請註明出處:http://blog.csdn.net/u012975705/article/details/48752377
app源碼下載地址:https://github.com/noyo/ChatRoom/tree/master
伺服器端代碼下載地址:http://download.csdn.net/detail/u012975705/9141251 Socket介紹
網路上的兩個程式通過一個雙向的通訊串連實現資料的交換,這個雙向鏈路的一端稱為一個Socket。Socket通常用來實現客戶方和服務方的串連。Socket是TCP/IP協議的一個十分流行的編程介面,一個Socket由一個IP地址和一個連接埠號碼唯一確定。
Server端Listen(監聽)某個連接埠是否有串連請求,Client端向Server 端發出Connect(串連)請求,Server端向Client端發回Accept(接受)訊息。一個串連就建立起來了。Server端和Client 端都可以通過Send,Write等方法與對方通訊。
對於一個功能齊全的Socket,都要包含以下基本結構,其工作過程包含以下四個基本的步驟:1、建立Socket;2、 開啟串連到Socket的輸入/出流;3、 按照一定的協議對Socket進行讀/寫操作;4、 關閉Socket.
java在包java.net中提供了兩個類Socket和ServerSocket,分別用來表示雙向串連的用戶端和服務端。這是兩個封裝得非常好的類,使用很方便。
Socket client = new Socket(“127.0.0.1”, 80);//第一個參數為主機ip,第二個參數為連接埠號碼
ServerSocket server = new ServerSocket(80);
注意,在選擇連接埠時,必須小心。每一個連接埠提供一種特定的服務,只有給出正確的連接埠,才 能獲得相應的服務。0~1023的連接埠號碼為系統所保留,例如http服務的連接埠號碼為80,telnet服務的連接埠號碼為21,ftp服務的連接埠號碼為23, 所以我們在選擇連接埠號碼時,最好選擇一個大於1023的數以防止發生衝突。
在建立socket時如果發生錯誤,將產生IOException,在程式中必須對之作出處理。所以在建立Socket或ServerSocket是必須捕獲或拋出例外。 聊天室編寫
就直接上代碼了,代碼中大部分地方都有注釋,要有什麼不懂得地方可以在評論的時候詢問。
1、用戶端代碼
ChatClient.java:package com.practice.noyet.chatroom.socket;import android.util.Log;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;/** * Created by noyet on 2015/9/26. */public class ChatClient { public Socket socket; /** 資料寫入伺服器端 */ public PrintWriter writer; /** 從伺服器讀取資料 */ public BufferedReader reader; public ChatClient() { createSocket(); } /** * 擷取ChatClient執行個體 * @return ChatClient */ public synchronized ChatClient getChatClient() { return new ChatClient(); } /** * 建立Socket */ public void createSocket() { try { /** 初始化Socket,參數:主機ip(伺服器主機ip) 連接埠號碼 */ socket = new Socket("192.168.1.142", 1314); /** 初始化寫資料流 */ writer = new PrintWriter(socket.getOutputStream()); /** 初始化讀資料流 */ reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (Exception e) { /** 列印錯誤資訊 */ printErrorInfo("ChatClient.createSocket", e); e.printStackTrace(); } } /** * 向伺服器發送訊息 * @param chatMsg 資訊內容 */ public void sendChatMsg(String chatMsg) { /** 將資料寫入伺服器端 */ writer.println(chatMsg); /** 重新整理輸出資料流(寫入伺服器),使Server馬上收到該字串 */ writer.flush(); } /** * 擷取從伺服器返回的資料 * @return String */ public String getChatMsg() { try { String str = reader.readLine(); return str; } catch (Exception e) { /** 列印錯誤資訊 */ printErrorInfo("ChatClient.getChatMsg", e); e.printStackTrace(); } return null; } /** * 關閉IO流 */ public void destroySocket() { try { if (reader != null) { reader.close(); } if (writer != null) { writer.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { /** 列印錯誤資訊 */ printErrorInfo("ChatClient.destroySocket", e); e.printStackTrace(); } } /** * 列印錯誤資訊 * @param tag 產生錯誤資訊的方法 * @param info 錯誤資訊 */ private void printErrorInfo(String tag, Exception info) { Log.d(tag + " Error", "Error: " + info); }}
2、app主Activity代碼
MainActivity.java:package com.practice.noyet.chatroom;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListView;import android.widget.TextView;import com.practice.noyet.chatroom.socket.ChatClient;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity implements View.OnClickListener { /** 帶清除標誌的用戶端A的資料輸入框 */ private ClearEditText aContent; /** 用戶端A的資料提交按鈕 */ private TextView aSend; /** 帶清除標誌的用戶端B的資料輸入框 */ private ClearEditText bContent; /** 用戶端B的資料提交按鈕 */ private TextView bSend; /** 顯示從伺服器端返回的資料 */ private ListView mListView; /** 使用者A的用戶端 */ private ChatClient clientA; /** 使用者B的用戶端 */ private ChatClient clientB; private ArrayAdapter<String> mAdapter; private List<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); initEvent(); } /** * 初始化控制項 */ private void initView() { new MyAsyncTask().execute(1); aContent = (ClearEditText) findViewById(R.id.a_client_cet); aSend = (TextView) findViewById(R.id.a_client_send); bContent = (ClearEditText) findViewById(R.id.b_client_cet); bSend = (TextView) findViewById(R.id.b_client_send); mListView = (ListView) findViewById(R.id.chat_content_listview); } /** * 初始化資料 */ private void initData() { list = new ArrayList<>(); mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list); mListView.setAdapter(mAdapter); } /** * 初始化監聽事件 */ private void initEvent() { aSend.setOnClickListener(this); bSend.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.a_client_send: //向伺服器發送訊息 clientA.sendChatMsg(aContent.getText().toString()); //擷取從伺服器返回的資料 new MyAsyncTask().execute(2); break; case R.id.b_client_send: //向伺服器發送訊息 clientB.sendChatMsg(bContent.getText().toString()); //擷取從伺服器返回的資料 new MyAsyncTask().execute(3); break; } } @Override protected void onDestroy() { super.onDestroy(); clientA.destroySocket(); clientB.destroySocket(); } private class MyAsyncTask extends AsyncTask<Integer, Integer, Integer> { @Override protected Integer doInBackground(Integer... integers) { if (integers[0] == 1) { clientA = new ChatClient(); clientB = new ChatClient(); } else if (integers[0] == 2) { list.add("Client A: " + clientA.getChatMsg()); } else if (integers[0] == 3) { list.add("Client B: " + clientA.getChatMsg()); } return integers[0]; } @Override protected void onPostExecute(Integer integer) { super.onPostExecute(integer); if (integer == 2 || integer == 3) { mAdapter.notifyDataSetChanged(); } } }}
3、擁有清除按鈕的自訂EditText代碼
ClearEditText.java:package com.practice.noyet.chatroom;import android.content.Context;import android.graphics.drawable.Drawable;import android.text.Editable;import android.text.TextWatcher;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.view.View.OnFocusChangeListener;import android.view.animation.Animation;import android.view.animation.CycleInterpolator;import android.view.animation.TranslateAnimation;import android.widget.EditText;public class ClearEditText extends EditText implements OnFocusChangeListener, TextWatcher { /** * 刪除按鈕的引用 */ private Drawable mClearDrawable; public ClearEditText(Context context) { this(context, null); } public ClearEditText(Context context, AttributeSet attrs) { /** 這裡構造方法也很重要,不加這個很多屬性不能再XML裡面定義 */ this(context, attrs, android.R.attr.editTextStyle); } public ClearEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } private void init() { /** 擷取EditText的DrawableRight,假如沒有設定我們就使用預設的圖片 */ mClearDrawable = getCompoundDrawables()[2]; if (mClearDrawable == null) { mClearDrawable = getResources() .getDrawable(R.drawable.del); } mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(), mClearDrawable.getIntrinsicHeight()); setClearIconVisible(false); setOnFocusChangeListener(this); addTextChangedListener(this); } /** * 因為我們不能直接給EditText設定點擊事件,所以我們用記住我們按下的位置來類比點擊事件 * 當我們按下的位置 在 EditText的寬度 - 表徵圖到控制項右邊的間距 - 表徵圖的寬度 和 * EditText的寬度 - 表徵圖到控制項右邊的間距之間我們就算點擊了表徵圖,豎直方向沒有考慮 */ @Override public boolean onTouchEvent(MotionEvent event) { if (getCompoundDrawables()[2] != null) { if (event.getAction() == MotionEvent.ACTION_UP) { boolean touchable = event.getX() > (getWidth() - getPaddingRight() - mClearDrawable.getIntrinsicWidth()) && (event.getX() < ((getWidth() - getPaddingRight()))); if (touchable) { this.setText(""); /** 晃動動畫 */ setShakeAnimation(); } } } return super.onTouchEvent(event); } /** * 當ClearEditText焦點發生變化的時候,判斷裡面字串長度設定清除表徵圖的顯示與隱藏 */ @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { setClearIconVisible(getText().length() > 0); } else { setClearIconVisible(false); } } /** * 設定清除表徵圖的顯示與隱藏,調用setCompoundDrawables為EditText繪製上去 * @param visible 刪除按鈕是否見 */ protected void setClearIconVisible(boolean visible) { Drawable right = visible ? mClearDrawable : null; setCompoundDrawables(getCompoundDrawables()[0], getCompoundDrawables()[1], right, getCompoundDrawables()[3]); } /** * 當輸入框裡面內容發生變化的時候回調的方法 */ @Override public void onTextChanged(CharSequence s, int start, int count, int after) { setClearIconVisible(s.length() > 0); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } /** * 設定晃動動畫 */ public void setShakeAnimation() { this.setAnimation(shakeAnimation(5)); } /** * 晃動動畫 * @param counts 1秒鐘晃動多少下 * @return Animation */ public static Animation shakeAnimation(int counts) { Animation translateAnimation = new TranslateAnimation(0, 10, 0, 0); translateAnimation.setInterpolator(new CycleInterpolator(counts)); translateAnimation.setDuration(1000); return translateAnimation; }}
4、介面布局
activity_main.xml:<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <LinearLayout android:id="@+id/aclient" android:gravity="center_vertical" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="用戶端A" android:textSize="16sp" android:layout_weight="2" android:layout_width="0dp" android:layout_height="wrap_content" /> <com.practice.noyet.chatroom.ClearEditText android:id="@+id/a_client_cet" android:paddingLeft="15dp" android:textSize="16sp" android:singleLine="true" android:textColorHint="@android:color/darker_gray" android:hint="請輸入要傳入伺服器的字串" android:background="@drawable/input" android:layout_weight="6" android:layout_width="0dp" android:layout_height="30dp" /> <TextView android:id="@+id/a_client_send" android:paddingLeft="5dp" android:text="發送" android:textSize="16sp" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:id="@+id/bclient" android:layout_marginTop="10dp" android:layout_below="@id/aclient" android:gravity="center_vertical" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:text="用戶端B" android:textSize="16sp" android:layout_weight="2" android:layout_width="0dp" android:layout_height="wrap_content" /> <com.practice.noyet.chatroom.ClearEditText android:id="@+id/b_client_cet" android:paddingLeft="15dp" android:textSize="16sp" android:singleLine="true" android:textColorHint="@android:color/darker_gray" android:hint="請輸入要傳入伺服器的字串" android:background="@drawable/input" android:layout_weight="6" android:layout_width="0dp" android:layout_height="30dp" /> <TextView android:id="@+id/b_client_send" android:paddingLeft="5dp" android:text="發送" android:textSize="16sp" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_marginTop="15dp" android:layout_below="@id/bclient" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:background="@drawable/content" android:id="@+id/chat_content_listview" android:dividerHeight="1dp" android:divider="@android:color/white" android:layout_width="match_parent" android:layout_height="match_parent"/>