
本文实例讲述了AndroID Socket通信传输实现方法。分享给大家供大家参考,具体如下:
1.开篇简介
Socket本质上就是Java封装了传输层上的TCP协议(注:UDP用的是DatagramSocket类)。要实现Socket的传输,需要构建客户端和服务器端。另外,传输的数据可以是字符串和字节。字符串传输主要用于简单的应用,比较复杂的应用(比如Java和C++进行通信),往往需要构建自己的应用层规则(类似于应用层协议),并用字节来传输。
2.基于字符串传输的Socket案例
1)服务器端代码(基于控制台的应用程序,模拟)
import java.io.BufferedReader;import java.io.BuffereDWriter;import java.io.IOException;import java.io.inputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.socket;import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Main { private static final int PORT = 9999; private List<Socket> mList = new ArrayList<Socket>(); private ServerSocket server = null; private ExecutorService mExecutorService = null; //thread pool public static voID main(String[] args) { new Main(); } public Main() { try { server = new ServerSocket(PORT); mExecutorService = Executors.newCachedThreadPool(); //create a thread pool System.out.println("服务器已启动..."); Socket clIEnt = null; while(true) { clIEnt = server.accept(); //把客户端放入客户端集合中 mList.add(clIEnt); mExecutorService.execute(new Service(clIEnt)); //start a new thread to handle the connection } }catch (Exception e) { e.printstacktrace(); } } class Service implements Runnable { private Socket socket; private BufferedReader in = null; private String msg = ""; public Service(Socket socket) { this.socket = socket; try { in = new BufferedReader(new inputStreamReader(socket.getinputStream())); //客户端只要一连到服务器,便向客户端发送下面的信息。 msg = "服务器地址:" +this.socket.getInetAddress() + "come toal:" +mList.size()+"(服务器发送)"; this.sendmsg(); } catch (IOException e) { e.printstacktrace(); } } @OverrIDe public voID run() { try { while(true) { if((msg = in.readline())!= null) { //当客户端发送的信息为:exit时,关闭连接 if(msg.equals("exit")) { System.out.println("ssssssss"); mList.remove(socket); in.close(); msg = "user:" + socket.getInetAddress() + "exit total:" + mList.size(); socket.close(); this.sendmsg(); break; //接收客户端发过来的信息msg,然后发送给客户端。 } else { msg = socket.getInetAddress() + ":" + msg+"(服务器发送)"; this.sendmsg(); } } } } catch (Exception e) { e.printstacktrace(); } } /** * 循环遍历客户端集合,给每个客户端都发送信息。 */ public voID sendmsg() { System.out.println(msg); int num =mList.size(); for (int index = 0; index < num; index ++) { Socket mSocket = mList.get(index); PrintWriter pout = null; try { pout = new PrintWriter(new BuffereDWriter( new OutputStreamWriter(mSocket.getoutputStream())),true); pout.println(msg); }catch (IOException e) { e.printstacktrace(); } } } }}2)AndroID客户端代码
package com.amaker.socket;import java.io.BufferedReader;import java.io.BuffereDWriter;import java.io.IOException;import java.io.inputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.socket;import androID.app.Activity;import androID.app.AlertDialog;import androID.content.DialogInterface;import androID.os.Bundle;import androID.os.Handler;import androID.os.Message;import androID.vIEw.VIEw;import androID.Widget.button;import androID.Widget.EditText;import androID.Widget.TextVIEw;public class SocketDemo extends Activity implements Runnable { private TextVIEw tv_msg = null; private EditText ed_msg = null; private button btn_send = null; // private button btn_login = null; private static final String HOST = "10.0.2.2"; private static final int PORT = 9999; private Socket socket = null; private BufferedReader in = null; private PrintWriter out = null; private String content = ""; //接收线程发送过来信息,并用TextVIEw显示 public Handler mHandler = new Handler() { public voID handleMessage(Message msg) { super.handleMessage(msg); tv_msg.setText(content); } }; @OverrIDe public voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.main); tv_msg = (TextVIEw) findVIEwByID(R.ID.TextVIEw); ed_msg = (EditText) findVIEwByID(R.ID.EditText01); btn_send = (button) findVIEwByID(R.ID.button02); try { socket = new Socket(HOST,PORT); in = new BufferedReader(new inputStreamReader(socket .getinputStream())); out = new PrintWriter(new BuffereDWriter(new OutputStreamWriter( socket.getoutputStream())),true); } catch (IOException ex) { ex.printstacktrace(); ShowDialog("login exception" + ex.getMessage()); } btn_send.setonClickListener(new button.OnClickListener() { @OverrIDe public voID onClick(VIEw v) { // Todo auto-generated method stub String msg = ed_msg.getText().toString(); if (socket.isConnected()) { if (!socket.isOutputShutdown()) { out.println(msg); } } } }); //启动线程,接收服务器发送过来的数据 new Thread(SocketDemo.this).start(); } /** * 如果连接出现异常,d出AlertDialog! */ public voID ShowDialog(String msg) { new AlertDialog.Builder(this).setTitle("notification").setMessage(msg) .setPositivebutton("ok",new DialogInterface.OnClickListener() { @OverrIDe public voID onClick(DialogInterface dialog,int which) { } }).show(); } /** * 读取服务器发来的信息,并通过Handler发给UI线程 */ public voID run() { try { while (true) { if (!socket.isClosed()) { if (socket.isConnected()) { if (!socket.isinputShutdown()) { if ((content = in.readline()) != null) { content += "\n"; mHandler.sendMessage(mHandler.obtainMessage()); } else { } } } } } } catch (Exception e) { e.printstacktrace(); } }}解析:除了isClose方法,Socket类还有一个isConnected方法来判断Socket对象是否连接成功。 看到这个名字,也许读者会产生误解。 其实isConnected方法所判断的并不是Socket对象的当前连接状态, 而是Socket对象是否曾经连接成功过,如果成功连接过,即使现在isClose返回true, isConnected仍然返回true。因此,要判断当前的Socket对象是否处于连接状态, 必须同时使用isClose和isConnected方法, 即只有当isClose返回false,isConnected返回true的时候Socket对象才处于连接状态。 虽然在大多数的时候可以直接使用Socket类或输入输出流的close方法关闭网络连接,但有时我们只希望关闭OutputStream或inputStream,而在关闭输入输出流的同时,并不关闭网络连接。这就需要用到Socket类的另外两个方法:shutdowninput和shutdownOutput,这两个方法只关闭相应的输入、输出流,而它们并没有同时关闭网络连接的功能。和isClosed、isConnected方法一样,Socket类也提供了两个方法来判断Socket对象的输入、输出流是否被关闭,这两个方法是isinputShutdown()和isOutputShutdown()。 shutdowninput和shutdownOutput并不影响Socket对象的状态。
2.基于字节的传输
基于字节传输的时候,只需要把相应的字符串和整数等类型转换为对应的网络字节进行传输即可。具体关于如何把其转换为网络字节,请参《Java整型数与网络字节序byte[]数组转换关系详解》。
更多关于AndroID相关内容感兴趣的读者可查看本站专题:《Android通信方式总结》、《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android多媒体 *** 作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家AndroID程序设计有所帮助。
总结以上是内存溢出为你收集整理的Android开发之Socket通信传输简单示例全部内容,希望文章能够帮你解决Android开发之Socket通信传输简单示例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)