布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.br.MySocketActivity">
<TextView
android:gravity="center"
android:text="简易聊天室"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="match_parent"
android:layout_height="150dp" android:id="@+id/textShow"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/editText"/>
<Button
android:text="发送消息"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="@+id/sendButton"/>
</LinearLayout>
Server端
package com.br;
import android.app.Service;
import android.util.Log;
import java.io.*;
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 {
private static final int PORT = 12345;
private List<Socket> socketList = new ArrayList<>();
private ServerSocket serverSocket = null;
private ExecutorService executorService = null;
public static void main(String[] args) {
new Server();
}
public Server(){
try{
serverSocket = new ServerSocket(PORT);
executorService = Executors.newCachedThreadPool();
System.out.println("服务端运行中...\n");
Socket client = null;
while (true){
client = serverSocket.accept();
socketList.add(client);
executorService.execute(new Service(client));
}
} catch (IOException 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()+" 加入了聊天室; "
+"当前在线人数:"+socketList.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("------------");
socketList.remove(socket);
in.close();
msg = "用户: "+this.socket.getInetAddress()+" 退出了聊天室\n"
+"当前在线人数:"+socketList.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:"+msg);
int num = socketList.size();
for (int i = 0; i <num ; i++) {
Socket mSocket = socketList.get(i);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream(),"UTF-8")),true);
out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Client端
package com.br;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class MySocketActivity extends AppCompatActivity implements Runnable{
private static final int SUCCESS = 0x123;
private static final String HOST = "127.0.0.1";
private static final int PORT = 12345;
private TextView textShow;
private EditText editText;
private Button sendButton;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String content = "";
private StringBuilder builder = null;
public Handler handler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == SUCCESS){
builder.append(content);
textShow.setText(builder.toString());
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_socket);
builder = new StringBuilder();
textShow = findViewById(R.id.textShow);
editText = findViewById(R.id.editText);
sendButton = findViewById(R.id.sendButton);
new Thread(){
@Override
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();
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String msg = editText.getText().toString();
if(socket.isConnected()){
if(!socket.isOutputShutdown()){
out.println(msg);
}
}
}
});
new Thread(MySocketActivity.this).start();
}
@Override
public void run() {
try{
Thread.sleep(1000);
while (true){
if(socket.isConnected()){
if(!socket.isInputShutdown()){
if((content = in.readLine())!=null){
content+="\n";
handler.sendEmptyMessage(SUCCESS);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}