标签:
上周在项目遇到一个接口需求就是通讯系列必须是socket,所以在这篇博客里面我想谈谈自己在socket编程的时候遇到的一些问题。
其实在android里面实现一个socket通讯是非常简单的,我们只需要在代码里面实现一个Socket对象,同时在该对象里面传进一个ip/port,同时设置一些超时时间就可以了。代码如下:
public class SocketThread extends Thread { private String ip = "192.168.129.1"; private int port = 12344; private String TAG = "socket thread"; private int timeout = 60000; private int maxsize = 256; public Socket client = null; OutputStream out; InputStream in; public boolean isRun = true; Handler inHandler; Handler outHandler; Context context; private String tagTip = "===Send==="; public SocketThread(Handler handlerin, Handler handlerout, Context context) { inHandler = handlerin; outHandler = handlerout; this.context = context; Log.i(TAG, "创建线程socket"); } public void conn() { try { client = new Socket(ip, port); client.setSoTimeout(timeout); client.setTcpNoDelay(true); in = client.getInputStream(); out = client.getOutputStream(); } catch (UnknownHostException e) { Log.i(TAG, "连接错误UnknownHostException 重新获取"); e.printStackTrace(); conn(); } catch (IOException e) { Log.i(TAG, "连接服务器io错误"); e.printStackTrace(); } catch (Exception e) { Log.i(TAG, "连接服务器错误Exception" + e.getMessage()); e.printStackTrace(); } } @Override public void run() { conn(); String line = ""; while (isRun) { try { if (client != null) { Log.i(TAG, "2.检测数据"); byte[] temp = new byte[maxsize]; int size = 0; while ((size = in.read(temp)) > 0) { Log.i(TAG, "收到数据"); byte[] res = new byte[size]; System.arraycopy(temp, 0, res, 0, size); for (int i = 0; i < size; i++) { line += res[i] + " "; } Message msg = inHandler.obtainMessage(); msg.obj = line; inHandler.sendMessage(msg); } } else { Log.i(TAG, "没有可用连接"); conn(); } } catch (Exception e) { Log.i(TAG, "数据接收错误" + e.getMessage()); e.printStackTrace(); } } } public void Send(byte[] mess) { try { if (client != null) { out.write(mess); out.flush(); Log.i(tagTip, "发送成功"); Message msg = outHandler.obtainMessage(); msg.obj = mess; msg.what = 1; outHandler.sendMessage(msg); } else { Log.i(TAG, "client 不存在"); Message msg = outHandler.obtainMessage(); msg.obj = mess; msg.what = 0; outHandler.sendMessage(msg); Log.i(TAG, "连接不存在重新连接"); conn(); } } catch (Exception e) { Log.i(tagTip, "send error"); e.printStackTrace(); } finally { Log.i(tagTip, "发送完毕"); } } public void close() { try { if (client != null) { in.close(); out.close(); client.close(); } } catch (Exception e) { Log.i(TAG, "close err"); e.printStackTrace(); } } }
上面的代码我就简单的实现了一个基于tcp协议的socket通讯,发送的内容信息是byte[],当然如果大家想要使用udp协议或者发送string字符串的话,那么代码还需要重新修改。相信网上的资料很多,这里就不贴代码了。
其实我最想说的是,socket通讯的过程中,如果发送的是byte[]的话,那么就需要很小心的注意byte前后顺序,同时拼接的过程中如果还涉及一定的加密的话。那么我们还需要很小心的验证加密算法的正确性。
有一次我问过部门头为什么要使用socket通讯呢?他的回答很简单就是安全性高,无其他理由!
标签:
原文地址:http://www.cnblogs.com/xiaocai20091687/p/android-xiaocai-socket.html