實作的效果圖:
先把我們的服務端跑起來:
接着把我們的程式分别跑到兩台模拟器上:
接下來我們來寫代碼:
首先是服務端,就是将讀寫socket的操作放到自定義線程當中,建立ServerSocket後,循環 調用accept方法,當有新用戶端接入,将socket加入集合當中,同時線上程池建立一個線程!
另外,在讀取資訊的方法中,對輸入字元串進行判斷,如果為bye字元串,将socket從集合中 移除,然後close掉!
Server.java:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
// 定義相關的參數,端口,存儲Socket連接配接的集合,ServerSocket對象
// 以及線程池
private static final int PORT = 12345;
private List<Socket> mList = new ArrayList<Socket>();
private ServerSocket server = null;
private ExecutorService myExecutorService = null;
public static void main(String[] args) {
new Server();
}
public Server() {
try {
server = new ServerSocket(PORT);
// 建立線程池
myExecutorService = Executors.newCachedThreadPool();
System.out.println("服務端運作中...\n");
Socket client = null;
while (true) {
client = server.accept();
mList.add(client);
myExecutorService.execute(new Service(client));
}
} catch (Exception e) {
e.printStackTrace();
}
}
class Service implements Runnable {
private Socket socket;
private BufferedReader in = null;
private String msg = "";
public Service(Socket socket) {
this.socket = socket;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msg = "使用者:" + this.socket.getInetAddress() + "~加入了聊天室" + "目前線上人數:" + mList.size();
this.sendmsg();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (true) {
if ((msg = in.readLine()) != null) {
if (msg.equals("bye")) {
System.out.println("~~~~~~~~~~~~~");
mList.remove(socket);
in.close();
msg = "使用者:" + socket.getInetAddress() + "退出:" + "目前線上人數:" + mList.size();
socket.close();
this.sendmsg();
break;
} else {
msg = socket.getInetAddress() + " 說: " + msg;
this.sendmsg();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 為連接配接上服務端的每個用戶端發送資訊
public void sendmsg() {
System.out.println(msg);
int num = mList.size();
for (int index = 0; index < num; index++) {
Socket mSocket = mList.get(index);
PrintWriter pout = null;
try {
pout = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8")), true);
pout.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
接着到用戶端,用戶端的難點在于要另外開辟線程的問題,因為Android不允許直接在 主線程中做網絡操作,而且不允許在主線程外的線程操作UI,這裡的做法是自己建立 一個線程,以及通過Hanlder來更新UI,實際開發不建議直接這樣做!!!
布局檔案:activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="小豬簡易聊天室" />
<TextView
android:id="@+id/txtshow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/editsend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/btnsend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="發送"
/>
</LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity implements Runnable {
// 定義相關變量,完成初始化
private TextView txtshow;
private EditText editsend;
private Button btnsend;
private static final String HOST = "172.16.2.54";
private static final int PORT = 12345;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String content = "";
private StringBuilder sb = null;
// 定義一個handler對象,用來重新整理界面
public Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
sb.append(content);
txtshow.setText(sb.toString());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb = new StringBuilder();
txtshow = (TextView) findViewById(R.id.txtshow);
editsend = (EditText) findViewById(R.id.editsend);
btnsend = (Button) findViewById(R.id.btnsend);
// 當程式一開始運作的時候就執行個體化Socket對象,與服務端進行連接配接,擷取輸入輸出流
// 因為4.0以後不能再主線程中進行網絡操作,是以需要另外開辟一個線程
new Thread() {
public void run() {
try {
socket = new Socket(HOST, PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
// 為發送按鈕設定點選事件
btnsend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = editsend.getText().toString();
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
out.println(msg);
}
}
}
});
new Thread(MainActivity.this).start();
}
// 重寫run方法,在該方法中輸入流的讀取
@Override
public void run() {
try {
while (true) {
if (socket.isConnected()) {
if (!socket.isInputShutdown()) {
if ((content = in.readLine()) != null) {
content += "\n";
handler.sendEmptyMessage(0x123);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}