Skip to content

Commit 2b92329

Browse files
author
qianlq
committed
🍭 feat(简易聊天室):添加简易聊天室代码
1 parent 1070b87 commit 2b92329

File tree

5 files changed

+259
-1
lines changed

5 files changed

+259
-1
lines changed

app/src/main/AndroidManifest.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
33
package="com.coderqian">
44

5+
<uses-permission android:name="android.permission.INTERNET" />
6+
57
<application
68
android:allowBackup="true"
79
android:icon="@mipmap/ic_launcher"
@@ -225,6 +227,14 @@
225227
</intent-filter>
226228
</activity>
227229

230+
<activity android:name=".chapter7.ChatActivity">
231+
<intent-filter>
232+
<action android:name="android.intent.action.VIEW" />
233+
234+
<category android:name="android.intent.category.LAUNCHER" />
235+
</intent-filter>
236+
</activity>
237+
228238
<provider
229239
android:name=".chapter6.providers.PeopleProvider"
230240
android:authorities="com.coderqian.chapter6.providers.PeopleProvider"

app/src/main/java/com/coderqian/MainActivity.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public class MainActivity extends EuclidActivity {
2121
"com.coderqian.chapter4.FragmentActivity,com.coderqian.chapter4.Fragment2Activity,com.coderqian.chapter4.IntentActivity,com.coderqian.chapter4.AnimatorActivity",
2222
"com.coderqian.chapter5.TweenActivity,com.coderqian.chapter5.FrameActivity,com.coderqian.chapter5.LeafLoadingActivity",
2323
"com.coderqian.chapter6.SQLiteActivity,com.coderqian.chapter6.ResolverActivity,com.coderqian.chapter6.StudentActivity",
24-
"com.coderqian.chapter7.ServiceActivity,com.coderqian.chapter7.BundleActivity", "", ""};
24+
"com.coderqian.chapter7.ServiceActivity,com.coderqian.chapter7.BundleActivity,com.coderqian.chapter7.ChatActivity", "", ""};
2525

2626
@Override
2727
protected void onCreate(Bundle savedInstanceState) {
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
package com.coderqian.chapter7;
2+
3+
import android.os.Bundle;
4+
import android.os.Handler;
5+
import android.os.Message;
6+
import android.support.v7.app.AppCompatActivity;
7+
import android.view.View;
8+
import android.widget.Button;
9+
import android.widget.EditText;
10+
import android.widget.TextView;
11+
12+
import com.coderqian.R;
13+
14+
import java.io.BufferedReader;
15+
import java.io.BufferedWriter;
16+
import java.io.IOException;
17+
import java.io.InputStreamReader;
18+
import java.io.OutputStreamWriter;
19+
import java.io.PrintWriter;
20+
import java.net.Socket;
21+
22+
/**
23+
* @author qianliqing
24+
* @since 2018/11/7 6:39 PM
25+
26+
*/
27+
28+
public class ChatActivity extends AppCompatActivity implements Runnable {
29+
30+
private TextView txtshow;
31+
private EditText editsend;
32+
private Button btnsend;
33+
private static final String HOST = "172.20.10.7";
34+
private static final int PORT = 12345;
35+
private Socket socket = null;
36+
private BufferedReader in = null;
37+
private PrintWriter out = null;
38+
private String content = "";
39+
private StringBuilder sb = null;
40+
41+
// 定义一个handler对象,用来刷新界面
42+
public Handler handler = new Handler() {
43+
public void handleMessage(Message msg) {
44+
if (msg.what == 0x123) {
45+
sb.append(content);
46+
txtshow.setText(sb.toString());
47+
}
48+
}
49+
};
50+
51+
@Override
52+
protected void onCreate(Bundle savedInstanceState) {
53+
super.onCreate(savedInstanceState);
54+
setContentView(R.layout.activity_chat);
55+
sb = new StringBuilder();
56+
txtshow = (TextView) findViewById(R.id.txtshow);
57+
editsend = (EditText) findViewById(R.id.editsend);
58+
btnsend = (Button) findViewById(R.id.btnsend);
59+
60+
// 当程序一开始运行的时候就实例化Socket对象,与服务端进行连接,获取输入输出流
61+
// 因为4.0以后不能再主线程中进行网络操作,所以需要另外开辟一个线程
62+
new Thread() {
63+
64+
@Override
65+
public void run() {
66+
try {
67+
socket = new Socket(HOST, PORT);
68+
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
69+
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
70+
} catch (IOException e) {
71+
e.printStackTrace();
72+
}
73+
}
74+
}.start();
75+
76+
// 为发送按钮设置点击事件
77+
btnsend.setOnClickListener(new View.OnClickListener() {
78+
79+
@Override
80+
public void onClick(View v) {
81+
final String msg = editsend.getText().toString();
82+
if (socket.isConnected()) {
83+
if (!socket.isOutputShutdown()) {
84+
System.out.println(msg);
85+
out.println(msg);
86+
}
87+
}
88+
}
89+
});
90+
new Thread(ChatActivity.this).start();
91+
}
92+
93+
// 重写run方法,在该方法中输入流的读取
94+
@Override
95+
public void run() {
96+
try {
97+
while (true) {
98+
if (socket.isConnected()) {
99+
if (!socket.isInputShutdown()) {
100+
if ((content = in.readLine()) != null) {
101+
content += "\n";
102+
handler.sendEmptyMessage(0x123);
103+
}
104+
}
105+
}
106+
}
107+
} catch (Exception e) {
108+
e.printStackTrace();
109+
}
110+
}
111+
112+
}
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
package com.coderqian.chapter7.chat;
2+
3+
import java.io.BufferedReader;
4+
import java.io.BufferedWriter;
5+
import java.io.IOException;
6+
import java.io.InputStreamReader;
7+
import java.io.OutputStreamWriter;
8+
import java.io.PrintWriter;
9+
import java.net.ServerSocket;
10+
import java.net.Socket;
11+
import java.util.ArrayList;
12+
import java.util.List;
13+
import java.util.concurrent.ExecutorService;
14+
import java.util.concurrent.Executors;
15+
16+
/**
17+
* @author qianliqing
18+
* @since 2018/11/7 6:48 PM
19+
20+
*/
21+
22+
public class Server {
23+
// 定义相关的参数,端口,存储Socket连接的集合,ServerSocket对象
24+
// 以及线程池
25+
private static final int PORT = 12345;
26+
private List<Socket> mList = new ArrayList<Socket>();
27+
private ServerSocket server = null;
28+
private ExecutorService myExecutorService = null;
29+
30+
public static void main(String[] args) {
31+
new Server();
32+
}
33+
34+
public Server() {
35+
try {
36+
server = new ServerSocket(PORT);
37+
// 创建线程池
38+
myExecutorService = Executors.newCachedThreadPool();
39+
System.out.println("服务端运行中...\n");
40+
Socket client = null;
41+
while (true) {
42+
client = server.accept();
43+
mList.add(client);
44+
myExecutorService.execute(new Service(client));
45+
}
46+
47+
} catch (Exception e) {
48+
e.printStackTrace();
49+
}
50+
}
51+
52+
class Service implements Runnable {
53+
private Socket socket;
54+
private BufferedReader in = null;
55+
private String msg = "";
56+
57+
public Service(Socket socket) {
58+
this.socket = socket;
59+
try {
60+
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
61+
msg = "用户:" + this.socket.getInetAddress() + "~加入了聊天室" + "当前在线人数:" + mList.size();
62+
this.sendmsg();
63+
} catch (IOException e) {
64+
e.printStackTrace();
65+
}
66+
}
67+
68+
@Override
69+
public void run() {
70+
try {
71+
while (true) {
72+
if ((msg = in.readLine()) != null) {
73+
if (msg.equals("bye")) {
74+
System.out.println("~~~~~~~~~~~~~");
75+
mList.remove(socket);
76+
in.close();
77+
msg = "用户:" + socket.getInetAddress() + "退出:" + "当前在线人数:" + mList.size();
78+
socket.close();
79+
this.sendmsg();
80+
break;
81+
} else {
82+
msg = socket.getInetAddress() + " 说: " + msg;
83+
this.sendmsg();
84+
}
85+
}
86+
}
87+
} catch (Exception e) {
88+
e.printStackTrace();
89+
}
90+
}
91+
92+
// 为连接上服务端的每个客户端发送信息
93+
public void sendmsg() {
94+
System.out.println(msg);
95+
int num = mList.size();
96+
for (int index = 0; index < num; index++) {
97+
Socket mSocket = mList.get(index);
98+
PrintWriter pout = null;
99+
try {
100+
pout = new PrintWriter(
101+
new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8")), true);
102+
pout.println(msg);
103+
} catch (IOException e) {
104+
e.printStackTrace();
105+
}
106+
}
107+
}
108+
}
109+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3+
android:layout_width="match_parent"
4+
android:layout_height="match_parent"
5+
android:orientation="vertical">
6+
7+
<TextView
8+
android:layout_width="wrap_content"
9+
android:layout_height="wrap_content"
10+
android:text="简易聊天室" />
11+
12+
<TextView
13+
android:id="@+id/txtshow"
14+
android:layout_width="match_parent"
15+
android:layout_height="wrap_content" />
16+
17+
<EditText
18+
android:id="@+id/editsend"
19+
android:layout_width="match_parent"
20+
android:layout_height="wrap_content" />
21+
22+
<Button
23+
android:id="@+id/btnsend"
24+
android:layout_width="match_parent"
25+
android:layout_height="wrap_content"
26+
android:text="发送" />
27+
</LinearLayout>

0 commit comments

Comments
 (0)