文章目录

思路

【完成群聊天室】
服务端:
每当接收到客户端发来的消息后,需要给每一个在线的客户都输出一遍

List<Socket> sockets;

main{
socket= ss.accept();
sockets.add(socket);
new Thread(){
run(){

}
}.start();
}

客户端:
建立连接、发送消息、接收并显示消息

注意:
网络编程注意事项:
1、所有网络操作都需要在工作线程中执行
2、网络操作需要添加权限

实现

按照以上思路完成服务端 ChatServer

public class ChatServer {
private List<Socket> sockets = new ArrayList<Socket>();

/**
* 开启服务
*
* @throws IOException
*/
public void startServer() throws IOException {
System.out.println("服务已启动...");
//启动服务
ServerSocket ss = new ServerSocket(8888);
//不断接收从客户端发来的消息
while (true) {
//阻塞执行,接收客户端连接
Socket socket = ss.accept();
sockets.add(socket);
//想要并发处理的话,需要开启线程
new WorkThread(socket).start();
}
}

/**
* 工作线程
* 接收客户端的消息,并给每个线程发一遍
*/
class WorkThread extends Thread {
private Socket socket;

public WorkThread(Socket socket) {
this.socket = socket;
}

public void run() {
try {
DataInputStream dis = new DataInputStream(socket.getInputStream());
while (true) {
String message = dis.readUTF();
//给每一个客户端都发一遍
for (int i = 0; i < sockets.size(); i++) {
Socket s = sockets.get(i);
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(message);
dos.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
//当开启一条线程后,线程会等待客户端发消息
//在等待的过程中,可能出现异常,比如连接中断,就会抛出connection reset的异常
//就会走到这里

System.out.println("连接中断");
//把当前socket对象从集合中移除
sockets.remove(socket);
}
}
}

public static void main(String[] args) {
ChatServer server = new ChatServer();
try {
server.startServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

布局文件activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
android:id="@+id/et_ip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/btn_ip" />

<Button
android:id="@+id/btn_ip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="确定" />

<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/btn_message"
android:layout_below="@+id/btn_ip" />

<Button
android:id="@+id/btn_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:text="确定" />

<EditText
android:id="@+id/et_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="@+id/btn_message" />
</RelativeLayout>

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText et_ip;
private EditText et_message;
private Button btn_ip;
private Button btn_message;
private ListView listview;
private Socket socket;

private DataInputStream dis;
private DataOutputStream dos;

private List<String> messages = new ArrayList<>();
private ArrayAdapter<String> adapter;

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case HANDLER_CONNECT_SUCCESS://连接成功
Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
et_ip.setEnabled(false);
btn_ip.setEnabled(false);
break;
case HANDLER_MESSAGE_RECEIVED://接受到消息
String message = (String) msg.obj;
messages.add("小明:" + message);
//更新adapter
adapter.notifyDataSetChanged();
//显示最后一条
listview.setSelection(messages.size() - 1);
break;
}
}
};

private static final int HANDLER_CONNECT_SUCCESS = 1;
private static final int HANDLER_MESSAGE_RECEIVED = 2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setViews();
//设置适配器
setAdapter();
}

private void setAdapter() {
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, messages);
listview.setAdapter(adapter);
}

private void setViews() {
et_ip = findViewById(R.id.et_ip);
et_message = findViewById(R.id.et_message);
btn_ip = findViewById(R.id.btn_ip);
btn_message = findViewById(R.id.btn_message);
listview = findViewById(R.id.listview);

btn_ip.setOnClickListener(this);
btn_message.setOnClickListener(this);
}

@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_ip:
//建立连接
new Thread() {
@Override
public void run() {
try {
connect();
} catch (IOException e) {
e.printStackTrace();
//连接建立失败
}
}
}.start();
break;
case R.id.btn_message:
//发送消息
new Thread() {
@Override
public void run() {
try {
sendMessage();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
break;
}
}

private void sendMessage() throws IOException {
String text = et_message.getText().toString();
dos.writeUTF(text);
dos.flush();
}

/**
* 读取服务端发回的消息的工作线程
*/
class ReadThread extends Thread {
//run方法执行完毕后,线程也就销毁了
//垃圾回收机制会回收
@Override
public void run() {
/*while (true){
try {
String message = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
//当断开连接,并不会跳出while循环,所以改成以下写法
}
}*/
try {
while (true) {
String message = dis.readUTF();
Log.i("info", "message:" + message);
//更新ListView,给handler发消息
Message msg = new Message();
msg.what = HANDLER_MESSAGE_RECEIVED;
msg.obj = message;
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
//连接异常,断开
Log.e("error", "连接出错,读不了数据了,看着办吧");
}
}
}

private void connect() throws IOException {
String ip = et_ip.getText().toString();
socket = new Socket(ip, 8888);

dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
//连接成功,发消息给主线程Handler 更新UI
handler.sendEmptyMessage(HANDLER_CONNECT_SUCCESS);
//启动读取消息的工作线程
new ReadThread().start();
}

@Override
protected void onDestroy() {
super.onDestroy();
if (socket != null) {
try {
//socket关掉后,流也就关掉了
//而客户端还有线程正等着读取数据,所以也需要处理下
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

AndroidManifest增加权限

<uses-permission android:name="android.permission.INTERNET"/>

运行步骤
1、用 IntelliJ IDEA 运行​​​ChatServer​​​【达内课程】利用Socket实现群聊_socket

2、查看自己电脑 ip
cmd 中执行​​​ipconfig​​​【达内课程】利用Socket实现群聊_android_02

3、修改​​MainActivity​​中,以下代码,把 message 前增加一个称呼,例如“小明”,运行在一台模拟机中

private void sendMessage() throws IOException {
String text = et_message.getText().toString();
dos.writeUTF("小明:\n"+text);
dos.flush();
}

4、修改 MainActivity 中 3 步骤代码中的称呼,改为“小红”,运行在另一台模拟机中

5、都输入 ip 地址确保连接成功

5、开始尬聊

【达内课程】利用Socket实现群聊_android_03