1.服务端开发
创建一个Java程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
public
class
MyServer {
// 定义保存所有的Socket,与客户端建立连接得到一个Socket
public
static
List<Socket> socketList =
new
ArrayList<Socket>();
public
static
void
main(String[] args)
throws
IOException {
ServerSocket server =
new
ServerSocket(
8888
);
while
(
true
) {
System.out.println(
"start listening port 8888"
);
Socket socket = server.accept();
System.out.println(
"connect succeed."
);
socketList.add(socket);
//每当客户端连接之后启动一条ServerThread线程为该客户端服务
new
Thread(
new
MyServerRunnable(socket)).start();
}
}
public
static
class
MyServerRunnable
implements
Runnable {
// 定义当前线程处理的Socket
Socket socket =
null
;
// 该线程所处理的Socket所对应的输入流
BufferedReader bufferedReader =
null
;
public
MyServerRunnable(Socket socket) {
this
.socket = socket;
try
{
// 将服务器端的输入流的数据放入读Buffer中
bufferedReader =
new
BufferedReader(
new
InputStreamReader(
socket.getInputStream()));
}
catch
(Exception e) {
e.printStackTrace();
}
}
@Override
public
void
run() {
String content =
null
;
// 采用循环不断的从Socket中读取客户端发送过来的数据
while
((content = readFromClient()) !=
null
) {
// 遍历socketList中的每一个Socket,将读取的内容向每个Socket发送一次
for
(Socket socket : MyServer.socketList) {
OutputStream outputStream;
try
{
outputStream = socket.getOutputStream();
outputStream.write((
"Server: "
+ content +
"\n"
).getBytes(
"utf-8"
));
}
catch
(IOException e) {
e.printStackTrace();
}
}
}
}
// 定义读取客户端的信息
public
String readFromClient() {
try
{
return
bufferedReader.readLine();
}
catch
(Exception e) {
e.printStackTrace();
}
return
null
;
}
}
}
|
2. 创建一个Android程序
1) Layout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:tools=
"http://schemas.android.com/tools"
android:layout_width=
"match_parent"
android:layout_height=
"match_parent"
android:gravity=
"center"
android:orientation=
"vertical"
tools:context=
".MainActivity"
>
<TextView
android:id=
"@+id/show"
android:layout_width=
"wrap_content"
android:layout_height=
"wrap_content"
android:text=
"显示接收到服务器端数据"
/>
<Button
android:id=
"@+id/send"
android:layout_width=
"match_parent"
android:layout_height=
"wrap_content"
android:text=
"发送数据到服务器端"
/>
</LinearLayout>
|
2)ClientThread类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
package
com.example.testclient;
import
java.io.BufferedReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.io.OutputStream;
import
java.net.InetSocketAddress;
import
java.net.Socket;
import
java.net.SocketTimeoutException;
import
android.os.Handler;
import
android.os.Looper;
import
android.os.Message;
import
android.util.Log;
public
class
ClientThread
implements
Runnable {
private
Socket s;
// 定义向UI线程发送消息的Handler对象
Handler handler;
// 定义接收UI线程的Handler对象
Handler revHandler;
// 该线程处理Socket所对用的输入输出流
BufferedReader br =
null
;
OutputStream os =
null
;
public
ClientThread(Handler handler) {
this
.handler = handler;
}
@Override
public
void
run() {
s =
new
Socket();
Log.d(
"111111111111"
,
"@@@@@@@@@@@@@@@@@@@@"
);
try
{
//192.168.0.26 为PC IP地址。<br><br> s.connect(new InetSocketAddress("192.168.0.26", 8888), 5000);
Log.d(
"111111111111"
,
"$$"
);
br =
new
BufferedReader(
new
InputStreamReader(s.getInputStream()));
os = s.getOutputStream();
// 启动一条子线程来读取服务器相应的数据
new
Thread() {
@Override
public
void
run() {
String content =
null
;
// 不断的读取Socket输入流的内容
try
{
while
((content = br.readLine()) !=
null
) {
// 每当读取到来自服务器的数据之后,发送的消息通知程序
// 界面显示该数据
Message msg =
new
Message();
msg.what =
0x123
;
msg.obj = content;
handler.sendMessage(msg);
Log.d(
"111111111111"
, content);
}
}
catch
(IOException io) {
io.printStackTrace();
}
}
}.start();
// 为当前线程初始化Looper
Looper.prepare();
// 创建revHandler对象
revHandler =
new
Handler() {
@Override
public
void
handleMessage(Message msg) {
// 接收到UI线程的中用户输入的数据
if
(msg.what ==
0x345
) {
// 将用户在文本框输入的内容写入网络
try
{
os.write((
"Client"
+ msg.obj.toString() +
"\r\n"
)
.getBytes(
"utf-8"
));
}
catch
(Exception e) {
e.printStackTrace();
}
}
}
};
// 启动Looper
Looper.loop();
}
catch
(SocketTimeoutException e) {
Message msg =
new
Message();
msg.what =
0x123
;
msg.obj =
"网络连接超时!"
;
handler.sendMessage(msg);
}
catch
(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
3. MainActivity
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
public
class
MainActivity
extends
Activity {
Handler handler;
// 定义与服务器通信的子线程
ClientThread clientThread;
TextView show;
Button send;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (TextView)
this
.findViewById(R.id.show);
send = (Button)
this
.findViewById(R.id.send);
send.setOnClickListener(
new
View.OnClickListener() {
@Override
public
void
onClick(View arg0) {
// TODO Auto-generated method stub
try
{
// 当用户按下按钮之后,将用户输入的数据封装成Message
// 然后发送给子线程Handler
Message msg =
new
Message();
msg.what =
0x345
;
msg.obj =
"Android 网络编程--Socket通信编程"
;
clientThread.revHandler.sendMessage(msg);
}
catch
(Exception e) {
e.printStackTrace();
}
}
});
handler =
new
Handler() {
@Override
public
void
handleMessage(Message msg) {
// 如果消息来自子线程
if
(msg.what ==
0x123
) {
// 将读取的内容追加显示在文本框中
show.append(
"\n"
+ msg.obj.toString());
show.setTextSize(
50
);
}
}
};
clientThread =
new
ClientThread(handler);
// 客户端启动ClientThread线程创建网络连接、读取来自服务器的数据
new
Thread(clientThread).start();
}
}
|
参考:http://blog.csdn.net/thanksgining/article/details/43561053
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/p/5124061.html,如需转载请自行联系原作者