最近在实现socket通信,所以写个demo来简单实现下。我用了一种是原始的socket实现,另一种是MINA框架来实现的。

下载demo:http://download.csdn.net/detail/qq_29774291/9826648

一.先看第一种方法

a)、创建Socket对象,指明需要连接的服务器的地址和端口。

b)、建立连接后,通过输出流向服务器发送请求信息。

c)、通过输入流获取服务器的响应信息。

d)、关闭响应资源

如下是主要代码

package com.item.item.sock.socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress; /**
* Socket 通信
*/
public class MyServiceOne extends Service {
private Socket socket;
private BufferedReader in = null;
private BufferedWriter out = null;
private boolean close = true;
private Thread readThread; @Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
} @Override
public void onCreate() {
super.onCreate();
close = true;
new Thread(new Runnable() {
@Override
public void run() {
int count = 0;
for(;;){
try {
count++;
SocketAddress socketAddress = new InetSocketAddress(ConnectUtils.HOST,ConnectUtils.POST);
socket = new Socket();
socket.connect(socketAddress,10000);
if(socket.isConnected()){
System.out.println("socket 连接成功");
in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
out =new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
//发送一个消息
out.write("start");
out.flush();
//开启一个线程来读取服务器发来的消息
readThread.start();
break;
}
}catch (Exception e){
if(count > ConnectUtils.IDLE_TIME){
break;
}else {
SystemClock.sleep(5000);
}
}
}
}
}).start();
readThread = new Thread(new Runnable() {
@Override
public void run() {
while (close){
String readtext = readText(socket);
if(readtext !=null){
System.out.println("服务器发来的消息:" + readtext);
}
}
}
});
} private String readText(Socket socket) {
String string = null;
if(socket.isConnected()){
try {
char[] buffer = new char[8000];
int count = 0;
if((count = in.read(buffer)) > 0){
char[] temp = new char[count];
for(int i=0;i<count;i++){
temp[i] = buffer[i];
}
string = new String(temp);
}
}catch (Exception e){
string = null;
}
}
return string;
} @Override
public void onDestroy() {
super.onDestroy();
close = false;
if(socket != null){
try {
socket.close();
socket = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

二.第二种方法是用MINA框架实现的

package com.item.item.sock.socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log; import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.service.IoService;
import org.apache.mina.core.service.IoServiceListener;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector; import java.net.InetSocketAddress;
import java.nio.charset.Charset; /**
* 使用MINA框架实现socket通信
* 由于接受消息会阻塞Android线程,所以开在子线程中(同时将其放在Service中,让其在后台运行)
*/
public class MyServiceTwo extends Service {
private String TAG = "jiejie";
private IoSession session = null;
private MinaClientHandler minaClientHandler;
private NioSocketConnector connector = null;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
} @Override
public void onCreate() {
super.onCreate();
minaClientHandler = new MinaClientHandler();
new Thread(new Runnable() {
@Override
public void run() {
//创建连接客户端
connector = new NioSocketConnector();
//设置连接超时时间
connector.setConnectTimeoutMillis(30000);
//添加过滤器
connector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
//设置接收缓冲区大小
connector.getSessionConfig().setReadBufferSize(1024);
//设置处理器
connector.setHandler(minaClientHandler);
//设置默认方位地址
connector.setDefaultRemoteAddress(new InetSocketAddress(ConnectUtils.HOST,ConnectUtils.POST));
//添加重连监听
connector.addListener(new IoListener(){
@Override
public void sessionDestroyed(IoSession ioSession) throws Exception {
int count = 0;
for(;;){
try {
count++;
ConnectFuture future = connector.connect();
future.awaitUninterruptibly();//等待连接创建完成
session = future.getSession();//获取session
if(session.isConnected()){
System.out.println("断线了 但是又重连了");
count = 0;
break;
}
}catch (Exception e){
if(count > ConnectUtils.IDLE_TIME){
break;
}else {
SystemClock.sleep(5000);
}
}
}
}
});
for(;;){
try {
ConnectFuture future = connector.connect();
future.awaitUninterruptibly();
System.out.println("socket 连接成功");
session = future.getSession();
session.write("start");
break;
}catch (Exception e){
SystemClock.sleep(5000);
}
}
}
}).start();
} @Override
public void onDestroy() {
super.onDestroy();
connector.dispose();
} private class MinaClientHandler extends IoHandlerAdapter{
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
super.exceptionCaught(session, cause);
Log.d(TAG,"exceptionCaught--------" + cause);
} @Override
public void messageReceived(IoSession session, Object message) throws Exception {
super.messageReceived(session, message);
Log.d(TAG,"messageReceived---------" + message );
} @Override
public void messageSent(IoSession session, Object message) throws Exception {
super.messageSent(session, message);
Log.d(TAG,"messageSent-------" + message);
} @Override
public void sessionClosed(IoSession session) throws Exception {
super.sessionClosed(session);
Log.d(TAG,"sessionClosed-------");
} @Override
public void sessionCreated(IoSession session) throws Exception {
super.sessionCreated(session);
Log.d(TAG,"sessionCreated------" + session);
} @Override
public void sessionOpened(IoSession session) throws Exception {
super.sessionOpened(session);
Log.d(TAG,"sessionOpened---------");
}
} /**
* 创建一个监听器实现mina的IoServiceListener接口,里面的方法可以不用实现
*/
private class IoListener implements IoServiceListener{ @Override
public void serviceActivated(IoService ioService) throws Exception { } @Override
public void serviceIdle(IoService ioService, IdleStatus idleStatus) throws Exception { } @Override
public void serviceDeactivated(IoService ioService) throws Exception { } @Override
public void sessionCreated(IoSession ioSession) throws Exception { } @Override
public void sessionClosed(IoSession ioSession) throws Exception { } @Override
public void sessionDestroyed(IoSession ioSession) throws Exception { }
}
}

三.对于粘包的处理  是建立临时缓冲区来处理

 public synchronized void Decode(char[] data)
{
for (int i = 0; i < data.length; i++)
{
char byt = data[i];
this.temp.add(byt);
if (byt == '"')
{
if (!this.instring)
{
this.instring = true; }
else if (getPrev() != '\\')
{
this.instring = false;
}
} if (instring) continue;
if (byt == '}' || byt == ']')
{
end = true;
left--;
}
if (byt == '{' || byt == '[')
{
left++;
}
if ((left) < 0)
{
temp.clear();
this.instring = false;
this.left = 0;
continue;
} if (end && left == 0)
{
end = false;
char[] p =new char[temp.size()];
// temp.toArray(p) ;//完整协议包
for(int j =0; j< temp.size();j++){
p[j] = temp.get(j);
} // todo : log
// if (OnPackageHanded != null) {
// OnPackageHanded(package);
// }
if(this.HandledPackage.size()>100){ this.HandledPackage.poll();
}
this.HandledPackage.offer(p);
temp.clear();
this.instring = false;
this.left = 0;
continue;
} }
}

Socket for android 简单实例的更多相关文章

  1. JAVA SOCKET编程单线程简单实例

    服务端: package socketProgram; import java.io.BufferedReader;import java.io.IOException;import java.io. ...

  2. Socket使用及简单实例

    一.搭建服务器端 a).创建ServerSocket对象绑定监听端口. b).通过accept()方法监听客户端的请求. c).建立连接后,通过输入输出流读取客户端发送的请求信息. d).通过输出流向 ...

  3. 【转】Android Https服务器端和客户端简单实例

    转载地址:http://blog.csdn.net/gf771115/article/details/7827233 AndroidHttps服务器端和客户端简单实例 工具介绍 Eclipse3.7 ...

  4. 一个简单的Android小实例

    原文:一个简单的Android小实例 一.配置环境 1.下载intellij idea15 2.安装Android SDK,通过Android SDK管理器安装或卸载Android平台   3.安装J ...

  5. Android Fragment 简单实例

    Android上的界面展示都是通过Activity实现的.Activity实在是太经常使用了.我相信大家都已经很熟悉了,这里就不再赘述. 可是Activity也有它的局限性,相同的界面在手机上显示可能 ...

  6. android Jni NDK开发环境搭建及其简单实例的编写

    android  Jni  NDK开发环境搭建及其简单实例的编写 由于工作需要,需要采用开发想要的JNI,由于之前没有接触过安卓的开发,所以更加网上的帖子,学习了下.遇到了些问题,然后总结下学习过程中 ...

  7. Win Socket编程原理及简单实例

    [转]http://www.cnblogs.com/tornadomeet/archive/2012/04/11/2442140.html 使用Linux Socket做了小型的分布式,如Linux ...

  8. Linux C Socket编程原理及简单实例

    部分转自:http://goodcandle.cnblogs.com/archive/2005/12/10/294652.aspx 1.   什么是TCP/IP.UDP? 2.   Socket在哪里 ...

  9. SpringMVC笔记——SSM框架搭建简单实例

    落叶枫桥 博客园 首页 新随笔 联系 订阅 管理 SpringMVC笔记——SSM框架搭建简单实例 简介 Spring+SpringMVC+MyBatis框架(SSM)是比较热门的中小型企业级项目开发 ...

随机推荐

  1. Service Discovery protocol(SDP)

    locating services provided by Volume 3 , Part C , section 8 2.1sdp client-server architecture 2.2 se ...

  2. c# Equals方法

    很多C#的教材都会强调对象相等的概念.我们都知道,在C#的世界里存在两种等同性.一种是逻辑等同性:如果两个对象在逻辑上代表同样的值,则称他们具有逻辑等同性.另一种是引用等同性:如果两个引用指向同一个对 ...

  3. (转)Centos7上部署openstack ocata配置详解

    原文:http://www.cnblogs.com/yaohong/p/7601470.html 随笔-124  文章-2  评论-82  Centos7上部署openstack ocata配置详解 ...

  4. linux inotifywait 下监控是否有IO

    帮助: JDU:/host-001e67a8d50b /log/today # inotifywait -h inotifywait 3.14 Wait for a particular event ...

  5. unity代码创建草和模拟风的效果

    void Start() { Test4(); } //草 private Vector3[] grassArray = new Vector3[7]; private GameObject gras ...

  6. master线程的主循环,后台循环,刷新循环,暂停循环

    InnoDB存储引擎的主要工作都是在一个单独的后台线程master thread中完成的.master thread的线程优先级别最高.其内部由几个循环(loop)组成:主循环(loop).后台循环( ...

  7. WPF中用后台C#代码为TabItem设置Background属性

    TabItem tabItem = sender as TabItem; tabItem.Background = new ImageBrush(new BitmapImage(new Uri(@&q ...

  8. R语言 删除变量rm函数

    变量可以通过使用 rm()函数来删除.下面我们删除变量var.3.然后再打印变量时出现异常错误. rm(var.3) print(var.3) 当上面的代码执行时,它产生以下结果: [1] " ...

  9. Tomcat源码分析——启动与停止服务

    前言 熟悉Tomcat的工程师们,肯定都知道Tomcat是如何启动与停止的.对于startup.sh.startup.bat.shutdown.sh.shutdown.bat等脚本或者批处理命令,大家 ...

  10. TP2.1 加载扩展配置文件参数

    维护老项目真的恶心!!!!!!!!! TP3.2好像有这样一个配置参数,可以设置有那些扩展配置文件,系统会自动加载. 方法一: 'LOAD_EXT_CONFIG' => 'user,db',// ...