




已阅读5页,还剩4页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
android socket编程实例 android客户端通过socket与服务器进行通信可以分为以下几步:应用程序与服务器通信可以采用两种模式:TCP可靠通信 和UDP不可靠通信。(1)通过IP地址和端口实例化Socket,请求连接服务器: socket = new Socket(HOST, PORT); /host:为服务器的IP地址 port:为服务器的端口号(2)获取Socket流以进行读写,并把流包装进BufferWriter或者PrintWriter: PrintWriterout=newPrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream(),true); 这里涉及了三个类:socket.getOutputStream得到socket的输出字节流,OutputStreamWriter是字节流向字符流转换的桥梁,BufferWriter是字符流,然后再包装进PrintWriter。(3)对Socket进行读写 if (socket.isConnected() if (!socket.isOutputShutdown() out.println(msg); (4)关闭打开的流 out.close();在写代码的过程中一定要注意对socket 输入流 输出流的关闭下面是一个简单的例子:main.xmlhtml view plaincopy1. 2. 6. 11. 15. 16. 21. 22. 下面是android客户端的源代码:java view plaincopy1. packagecom.android.SocketDemo;2. 3. importjava.io.BufferedReader;4. importjava.io.BufferedWriter;5. importjava.io.IOException;6. importjava.io.InputStreamReader;7. importjava.io.OutputStreamWriter;8. importjava.io.PrintWriter;9. .Socket;10. 11. importandroid.app.Activity;12. importandroid.app.AlertDialog;13. importandroid.content.DialogInterface;14. importandroid.os.Bundle;15. importandroid.os.Handler;16. importandroid.os.Message;17. importandroid.view.View;18. importandroid.widget.Button;19. importandroid.widget.EditText;20. importandroid.widget.TextView;21. 22. publicclassSocketDemoextendsActivityimplementsRunnable23. privateTextViewtv_msg=null;24. privateEditTexted_msg=null;25. privateButtonbtn_send=null;26. /privateButtonbtn_login=null;27. privatestaticfinalStringHOST=23;28. privatestaticfinalintPORT=9999;29. privateSocketsocket=null;30. privateBufferedReaderin=null;31. privatePrintWriterout=null;32. privateStringcontent=;33. 34. /*Calledwhentheactivityisfirstcreated.*/35. Override36. publicvoidonCreate(BundlesavedInstanceState)37. super.onCreate(savedInstanceState);38. setContentView(R.layout.main);39. 40. tv_msg=(TextView)findViewById(R.id.TextView);41. ed_msg=(EditText)findViewById(R.id.EditText01);42. /btn_login=(Button)findViewById(R.id.Button01);43. btn_send=(Button)findViewById(R.id.Button02);44. 45. try46. socket=newSocket(HOST,PORT);47. in=newBufferedReader(newInputStreamReader(socket.getInputStream();48. out=newPrintWriter(newBufferedWriter(newOutputStreamWriter(49. socket.getOutputStream(),true);50. catch(IOExceptionex)51. ex.printStackTrace();52. ShowDialog(loginexception+ex.getMessage();53. 54. btn_send.setOnClickListener(newButton.OnClickListener()55. 56. Override57. publicvoidonClick(Viewv)58. /TODOAuto-generatedmethodstub59. Stringmsg=ed_msg.getText().toString();60. if(socket.isConnected()61. if(!socket.isOutputShutdown()62. out.println(msg);63. 64. 65. 66. );67. newThread(SocketDemo.this).start();68. 69. 70. publicvoidShowDialog(Stringmsg)71. newAlertDialog.Builder(this).setTitle(notification).setMessage(msg)72. .setPositiveButton(ok,newDialogInterface.OnClickListener()73. 74. Override75. publicvoidonClick(DialogInterfacedialog,intwhich)76. /TODOAuto-generatedmethodstub77. 78. 79. ).show();80. 81. 82. publicvoidrun()83. try84. while(true)85. if(socket.isConnected()86. if(!socket.isInputShutdown()87. if(content=in.readLine()!=null)88. content+=n;89. mHandler.sendMessage(mHandler.obtainMessage();90. else91. 92. 93. 94. 95. 96. catch(Exceptione)97. e.printStackTrace();98. 99. 100. 101. publicHandlermHandler=newHandler()102. publicvoidhandleMessage(Messagemsg)103. super.handleMessage(msg);104. tv_msg.setText(tv_msg.getText().toString()+content);105. 106. ;107. 下面是服务器端得java代码:java view plaincopy1. importjava.io.BufferedReader;2. importjava.io.BufferedWriter;3. importjava.io.IOException;4. importjava.io.InputStreamReader;5. importjava.io.OutputStreamWriter;6. importjava.io.PrintWriter;7. .ServerSocket;8. .Socket;9. importjava.util.ArrayList;10. importjava.util.List;11. importjava.util.concurrent.ExecutorService;12. importjava.util.concurrent.Executors;13. 14. 15. publicclassMain16. privatestaticfinalintPORT=9999;17. privateListmList=newArrayList();18. privateServerSocketserver=null;19. privateExecutorServicemExecutorService=null;/threadpool20. 21. publicstaticvoidmain(Stringargs)22. newMain();23. 24. publicMain()25. try26. server=newServerSocket(PORT);27. mExecutorService=Executors.newCachedThreadPool();/createathreadpool28. System.out.print(serverstart.);29. Socketclient=null;30. while(true)31. client=server.accept();32. mList.add(client);33. mExecutorService.execute(newService(client);/startanewthreadtohandletheconnection34. 35. catch(Exceptione)36. e.printStackTrace();37. 38. 39. classServiceimplementsRunnable40. privateSocketsocket;41. privateBufferedReaderin=null;42. privateStringmsg=;43. 44. publicService(Socketsocket)45. this.socket=socket;46. try47. in=newBufferedReader(newInputStreamReader(socket.getInputStream();48. msg=user+this.socket.getInetAddress()+cometoal:49. +mList.size();50. this.sendmsg();51. catch(IOExceptione)52. e.printStackTrace();53. 54. 55. 56. 57. Override58. publicvoidrun()59. /TODOAuto-generatedmethodstub60. try61. while(true)62. if(msg=in.readLine()!=null)63. if(msg.equals(exit)64. System.out.println(ssssssss);65. mList.remove(socket);66. in.close();67. msg=user:+socket.getInetAddress()68. +exittotal:+mList.size();69. socket.close();70. this.sendmsg();71. break;72. else73. msg=socket.getInetAddress()+:+msg;74. this.sendmsg();75. 76. 77. 78. catch(Exceptione)79. e.printStackTrace();80. 81. 82. 83. publicvoidsendmsg()84. System.out.println(msg);85. intnum=mList.size();86.
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025福建南平委党校教师招聘8人模拟试卷含答案详解
- 2025江苏师范大学招聘工作人员78人(第一批)考前自测高频考点模拟试题及参考答案详解
- 2025-2030中国啤酒消费升级背景下的产品结构优化策略研究报告
- 2025-2030中国啤酒冷链物流体系建设及配送效率提升与成本控制方案研究
- 2025-2030中国医药市场营销费用管控与合规审计报告
- 2025-2030中国医美光电设备效果评价标准与纠纷防范机制
- 2025-2030中国医疗AI辅助新药研发算法优化与专利布局分析
- 2025-2030中国医学影像人工智能诊断系统商业化落地可行性研究报告
- 2025-2030中国区块链技术在跨境支付领域的合规化应用场景探索报告
- 2025-2030中国制药用水系统验证要求与节能减排方案报告
- 人生的因拼搏而精彩课件
- 2025年国企综合笔试试题及答案
- 中药用药安全知识培训课件
- 老旧护栏加固施工方案
- 中国资源循环集团有限公司子公司招聘笔试题库2025
- 雨季行车安全培训
- 2025年青海海东通信工程师考试(通信专业实务终端与业务)高、中级考前题库及答案
- 《红星照耀中国》
- 2025年浙江省档案职称考试(档案高级管理实务与案例分析)综合能力测试题及答案
- 景区接待培训课件
- 部编人教版二年级上册语文全册教学设计(配2025年秋改版教材)
评论
0/150
提交评论