Android例子—基于socket实现简易聊天室

时间:2021-12-10 10:08:23

实现的效果图:

先把我们的服务端跑起来:

Android例子—基于socket实现简易聊天室

接着把我们的程序分别跑到两台模拟器上:

Android例子—基于socket实现简易聊天室

接下来我们来写代码:

首先是服务端,就是将读写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();
		}
	}
}