开发学院手机开发Android 开发 Android socket编程 以非阻塞I/O服务器及Service为... 阅读

Android socket编程 以非阻塞I/O服务器及Service为例

 2010-08-22 04:49:00 来源:WEB开发网   
核心提示:}public String readMessage(SocketChannel sc){int nBytes = 0;ByteBuffer buf = ByteBuffer.allocate(1024);try {nBytes = sc.read(buf);buf.flip();Charset charset = C

}

public String readMessage(SocketChannel sc)

{

int nBytes = 0;

ByteBuffer buf = ByteBuffer.allocate(1024);

try {

nBytes = sc.read(buf);

buf.flip();

Charset charset = Charset.forName("UTF-8");

CharsetDecoder decoder = charset.newDecoder();

CharBuffer charBuffer = decoder.decode(buf);

result = charBuffer.toString();

} catch (IOException e) {

result = "@@@@@ is going to say goodbye!";

}

return result;

}

public static void main(String args[])

{

YaoChatServer nb = new YaoChatServer();

try

{

nb.startServer();

}

catch (IOException e)

{

e.printStackTrace();

System.exit(-1);

}

}

}

Android客户端的Service类:

package com.android.Yao;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.channels.SocketChannel;

import java.nio.charset.CharacterCodingException;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.util.Collection;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.app.Service;

import android.content.Context;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

public class ReceiveMessage extends Service{

private SocketChannel client = null;

private InetSocketAddress isa = null;

上一页  1 2 3 4 5 6  下一页

Tags:Android socket 编程

编辑录入:coldstar [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接