Socket在Android中的应用

Android 提供的常用的网络编程包括针对TCP/IP协议的Socket通信。Socket是一种跨平台的编程方式,可以在异构语言之间进行通信。

Socket程序的开发原理,是要实现服务器端和客户端。

服务器,使用ServerSocket监听指定的端口,端口可以随意指定(由于1024以下的端口通常属于保留端口,在一些操作系统中不可以随意使用,所以建议使用大于1024的端口),等待客户连接请求,客户连接后,会话产生;在完成会话后,关闭连接。

客户端,使用Socket对网络上某一个服务器的某一个端口发出连接请求,一旦连接成功,打开会话;会话完成后,关闭Socket。客户端不需要指定打开的端口,通常临时的、动态的分配一个1024以上的端口。


下面是一个实现socket的例子:

服务器端代码:

  1. packagecom.socket;
  2. importjava.io.BufferedReader;
  3. importjava.io.InputStream;
  4. importjava.io.InputStreamReader;
  5. importjava.io.OutputStream;
  6. importjava.io.PrintWriter;
  7. importjava.net.ServerSocket;
  8. importjava.net.Socket;
  9. /**
  10. *comServer
  11. */
  12. publicclassMain{
  13. privateintServerPort=9999;
  14. privateServerSocketserversocket=null;
  15. privateOutputStreamoutputStream=null;
  16. privateInputStreaminputStream=null;
  17. privatePrintWriterprintWinter=null;
  18. privateSocketsocket=null;
  19. privateBufferedReaderreader=null;
  20. publicMain(){
  21. try{
  22. serversocket=newServerSocket(ServerPort);
  23. System.out.println("服务启动。。。");
  24. socket=serversocket.accept();
  25. System.out.println("客户已连接");
  26. }catch(Exceptionex){
  27. ex.printStackTrace();
  28. }
  29. try{
  30. outputStream=socket.getOutputStream();
  31. inputStream=socket.getInputStream();
  32. printWinter=newPrintWriter(outputStream,true);
  33. reader=newBufferedReader(newInputStreamReader(inputStream));
  34. BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
  35. while(true){
  36. Stringmessage=reader.readLine();
  37. System.out.println("client:"+message);
  38. if(message.equals("bye")||message.equals("Bye")){
  39. break;
  40. }
  41. message=in.readLine();
  42. printWinter.println(message);
  43. }
  44. outputStream.close();
  45. inputStream.close();
  46. socket.close();
  47. serversocket.close();
  48. System.out.print("Clientisdisconnected");
  49. }catch(Exceptione){
  50. e.printStackTrace();
  51. }finally{
  52. }
  53. }
  54. publicstaticvoidmain(String[]args){
  55. newMain();
  56. }


客服端代码:

  1. packagecom.Aina.Android;
  2. importjava.io.BufferedReader;
  3. importjava.io.BufferedWriter;
  4. importjava.io.InputStreamReader;
  5. importjava.io.OutputStreamWriter;
  6. importjava.io.PrintWriter;
  7. importjava.net.Socket;
  8. importandroid.app.Activity;
  9. importandroid.app.AlertDialog;
  10. importandroid.content.DialogInterface;
  11. importandroid.os.Bundle;
  12. importandroid.os.Handler;
  13. importandroid.os.Message;
  14. importandroid.util.Log;
  15. importandroid.view.View;
  16. importandroid.widget.Button;
  17. importandroid.widget.EditText;
  18. importandroid.widget.TextView;
  19. publicclassTestextendsActivityimplementsRunnable{
  20. /**Calledwhentheactivityisfirstcreated.*/
  21. privateTextViewtv_msg=null;
  22. privateEditTexted_msg=null;
  23. privateButtonbtn_send=null;
  24. privateButtonbtn_login=null;
  25. privatestaticfinalStringHOST="192.168.0.132";
  26. privatestaticfinalintPORT=9999;
  27. privateSocketsocket=null;
  28. privateBufferedReaderin=null;
  29. privatePrintWriterout=null;
  30. privateStringcontent="";
  31. @Override
  32. publicvoidonCreate(BundlesavedInstanceState){
  33. super.onCreate(savedInstanceState);
  34. setContentView(R.layout.main);
  35. tv_msg=(TextView)this.findViewById(R.id.TextView);
  36. ed_msg=(EditText)this.findViewById(R.id.EditText01);
  37. btn_login=(Button)this.findViewById(R.id.Button01);
  38. btn_send=(Button)this.findViewById(R.id.Button02);
  39. try{
  40. socket=newSocket(HOST,PORT);
  41. in=newBufferedReader(newInputStreamReader(socket
  42. .getInputStream()));
  43. out=newPrintWriter(newBufferedWriter(
  44. newOutputStreamWriter(socket.getOutputStream())),
  45. true);
  46. }catch(Exceptionex){
  47. ex.printStackTrace();
  48. ShowDialog("登陆异常:"+ex.getMessage());
  49. }
  50. btn_send.setOnClickListener(newButton.OnClickListener(){
  51. publicvoidonClick(Viewv){
  52. //TODOAuto-generatedmethodstub
  53. Stringmsg=ed_msg.getText().toString();
  54. if(socket.isConnected()){
  55. if(!socket.isOutputShutdown()){
  56. out.println(msg);
  57. }
  58. }
  59. }
  60. });
  61. newThread(this).start();
  62. }
  63. publicvoidShowDialog(Stringmsg){
  64. newAlertDialog.Builder(this).setTitle("提示").setMessage(msg)
  65. .setPositiveButton("OK",newDialogInterface.OnClickListener(){
  66. publicvoidonClick(DialogInterfacedialog,intwhich){
  67. //TODOAuto-generatedmethodstub
  68. }
  69. }).show();
  70. }
  71. publicvoidrun(){
  72. try{
  73. while(true){
  74. if(socket.isConnected()){
  75. if(!socket.isInputShutdown()){
  76. if((content=in.readLine())!=null){
  77. Log.i("TAG","++"+content);
  78. content+="\n";
  79. mHandler.sendMessage(mHandler.obtainMessage());
  80. }else{
  81. }
  82. }
  83. }
  84. }
  85. }catch(Exceptionex){
  86. ex.printStackTrace();
  87. }
  88. }
  89. publicHandlermHandler=newHandler(){
  90. publicvoidhandleMessage(Messagemsg){
  91. super.handleMessage(msg);
  92. Log.i("TAG","--"+msg);
  93. tv_msg.setText(tv_msg.getText().toString()+content);
  94. }
  95. };
  96. }


XML文件布局:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <TextViewandroid:id="@+id/TextView"android:singleLine="false"
  6. android:layout_width="fill_parent"
  7. android:layout_height="wrap_content"/>
  8. <EditTextandroid:hint="content"android:id="@+id/EditText01"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content">
  11. </EditText>
  12. <Buttonandroid:text="login"android:id="@+id/Button01"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content">
  15. </Button>
  16. <Buttonandroid:text="send"android:id="@+id/Button02"
  17. android:layout_width="fill_parent"
  18. android:layout_height="wrap_content">
  19. </Button>
  20. </LinearLayout>

先启动服务器端,再运行客户端程序。

注意:(一)即使服务器端和客户端在一台机器上运行,也不能使用ip地址:127.0.0.1,否则,程序会出现拒绝连接的错误。

(二)客户端和服务器端最好不要建在一个工程下,最好是分别建立工程,然后启动服务器端和客户端,否则会报Error: ShouldNotReachHere()错误。这是因为Android程序不是已main方法为程序的入口。

运行效果:

XML文件布局:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"android:layout_width="fill_parent"
  4. android:layout_height="fill_parent">
  5. <TextViewandroid:id="@+id/TextView"android:singleLine="false"
  6. android:layout_width="fill_parent"
  7. android:layout_height="wrap_content"/>
  8. <EditTextandroid:hint="content"android:id="@+id/EditText01"
  9. android:layout_width="fill_parent"
  10. android:layout_height="wrap_content">
  11. </EditText>
  12. <Buttonandroid:text="login"android:id="@+id/Button01"
  13. android:layout_width="fill_parent"
  14. android:layout_height="wrap_content">
  15. </Button>
  16. <Buttonandroid:text="send"android:id="@+id/Button02"
  17. android:layout_width="fill_parent"
  18. android:layout_height="wrap_content">
  19. </Button>
  20. </LinearLayout>

先启动服务器端,再运行客户端程序。

注意:(一)即使服务器端和客户端在一台机器上运行,也不能使用ip地址:127.0.0.1,否则,程序会出现拒绝连接的错误。

(二)客户端和服务器端最好不要建在一个工程下,最好是分别建立工程,然后启动服务器端和客户端,否则会报Error: ShouldNotReachHere()错误。这是因为Android程序不是已main方法为程序的入口。

运行效果:





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值