本文实例讲述了android编程之客户端通过socket与服务器通信的方法。分享给大家供大家参考,具体如下:
下面是一个demo,android客户端通过socket与服务器通信。
由于android里面可以完全使用java.io.*包和java.net.*包,那么,实际上,逻辑部分与j2se没有区别。只是ui代码不一样。
android客户端通过socket与服务器通信分为下面5步:
(1)通过ip地址和端口实例化socket,请求连接服务器;
(2)获取socket流以进行读写,并把流包装进bufferwriter或者printwriter
这里涉及了三个类:socket.getoutputstream得到socket的输出字节流,outputstreamwriter是字节流向字符流转换的桥梁,bufferwriter是字符流,然后再包装进printwriter。
(3)对socket进行读写
(4)关闭打开的流
完整工程代码如下:
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
|
package com.yarin.android.examples_08_04;
import java.io.bufferedreader;
import java.io.bufferedwriter;
import java.io.inputstreamreader;
import java.io.outputstreamwriter;
import java.io.printwriter;
import java.net.socket;
import android.app.activity;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.edittext;
import android.widget.textview;
public class activity01 extends activity
{
private final string debug_tag = "activity01" ;
private textview mtextview = null ;
private edittext medittext = null ;
private button mbutton = null ;
/** called when the activity is first created. */
@override
public void oncreate(bundle savedinstancestate)
{
super .oncreate(savedinstancestate);
setcontentview(r.layout.main);
mbutton = (button)findviewbyid(r.id.button01);
mtextview = (textview)findviewbyid(r.id.textview01);
medittext = (edittext)findviewbyid(r.id.edittext01);
//登陆
mbutton.setonclicklistener( new onclicklistener()
{
public void onclick(view v)
{
socket socket = null ;
string message = medittext.gettext().tostring() + "/r/n" ;
try
{
//创建socket
// socket = new socket("192.168.1.110",54321);
socket = new socket( "10.14.114.127" , 54321 ); //ip:10.14.114.127,端口54321
//向服务器发送消息
printwriter out = new printwriter( new bufferedwriter( new outputstreamwriter(socket.getoutputstream())), true );
out.println(message);
//接收来自服务器的消息
bufferedreader br = new bufferedreader( new inputstreamreader(socket.getinputstream()));
string msg = br.readline();
if ( msg != null )
{
mtextview.settext(msg);
}
else
{
mtextview.settext( "数据错误!" );
}
//关闭流
out.close();
br.close();
//关闭socket
socket.close();
}
catch (exception e)
{
// todo: handle exception
log.e(debug_tag, e.tostring());
}
}
});
}
}
|
布局文件main.xml
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
|
<?xml version= "1.0" encoding= "utf-8" ?>
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"
android:orientation= "vertical"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent"
>
<textview
android:id= "@+id/textview01"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:text= "这里显示接收到服务器发来的信息"
/>
<edittext
android:id= "@+id/edittext01"
android:text= "输入要发送的内容"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" >
</edittext>
<button
android:id= "@+id/button01"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:text= "发送"
/>
</linearlayout>
|
androidmanifest.xml文件如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?xml version= "1.0" encoding= "utf-8" ?>
<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
package = "com.yarin.android.examples_08_04"
android:versioncode= "1"
android:versionname= "1.0" >
<application android:icon= "@drawable/icon" android:label= "@string/app_name" >
<activity android:name= ".activity01"
android:label= "@string/app_name" >
<intent-filter>
<action android:name= "android.intent.action.main" />
<category android:name= "android.intent.category.launcher" />
</intent-filter>
</activity>
</application>
<uses-permission android:name= "android.permission.internet" ></uses-permission>
<uses-sdk android:minsdkversion= "5" />
</manifest>
|
当然,还有服务器端得代码
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
|
package com.yarin.android.examples_08_04;
import java.io.bufferedreader;
import java.io.bufferedwriter;
import java.io.inputstreamreader;
import java.io.outputstreamwriter;
import java.io.printwriter;
import java.net.serversocket;
import java.net.socket;
public class server implements runnable
{
public void run()
{
try
{
//创建serversocket
serversocket serversocket = new serversocket( 54321 );
while ( true )
{
//接受客户端请求
socket client = serversocket.accept();
system.out.println( "accept" );
try
{
//接收客户端消息
bufferedreader in = new bufferedreader( new inputstreamreader(client.getinputstream()));
string str = in.readline();
system.out.println( "read:" + str);
//向服务器发送消息
printwriter out = new printwriter( new bufferedwriter( new outputstreamwriter(client.getoutputstream())), true );
out.println( "server message" );
//关闭流
out.close();
in.close();
}
catch (exception e)
{
system.out.println(e.getmessage());
e.printstacktrace();
}
finally
{
//关闭
client.close();
system.out.println( "close" );
}
}
}
catch (exception e)
{
system.out.println(e.getmessage());
}
}
//main函数,开启服务器
public static void main(string a[])
{
thread desktopserverthread = new thread( new server());
desktopserverthread.start();
}
}
|
先开启服务器代码
java server即可
然后启动android模拟器。运行结果
这是android客户端。输入12345,点击发送:
这是服务器端收到的消息
希望本文所述对大家android程序设计有所帮助。