一台手机作为server,另一台作为client,使用了Mina框架。
一. Server端代码如下:
NioSocketAcceptor localNioSocketAcceptor = new NioSocketAcceptor();
TextLineCodecFactory localTextLineCodecFactory = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), "/r/n");
localTextLineCodecFactory.setDecoderMaxLineLength(10240);
localTextLineCodecFactory.setEncoderMaxLineLength(10240);
localNioSocketAcceptor.getFilterChain().addLast("textProtocol", new ProtocolCodecFilter(localTextLineCodecFactory));
localNioSocketAcceptor.getSessionConfig().setReadBufferSize(2048);
localNioSocketAcceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
((NioSocketAcceptor)localNioSocketAcceptor).setReuseAddress(true);
localNioSocketAcceptor.setHandler(new ServerHandler(this.context));
try
{
localNioSocketAcceptor.bind(new InetSocketAddress(8801));
Toast.makeText(this.context, "服务器启动成功,端口号:" + 8801, Toast.LENGTH_SHORT).show();
return;
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
}
监听Handler类:
public class ServerHandler extends IoHandlerAdapter {
private Context context;
public ServerHandler(Context paramContext) {
this.context = paramContext;
}
public void exceptionCaught(IoSession paramIoSession, Throwable paramThrowable)
throws Exception {
}
public void messageReceived(IoSession paramIoSession, Object paramObject)
throws Exception {
final String str = paramObject.toString();
((Activity) this.context).runOnUiThread(new Runnable() {
public void run() {
if (str != null) ;
try {
KeyWord localKeyWord = GsonUtils.jsonToBean(str,KeyWord.class);
EventBus.getDefault().post(localKeyWord);
return;
} catch (Exception localException) {
}
}
});
}
public void messageSent(IoSession paramIoSession, Object paramObject)
throws Exception {
Toast.makeText(this.context, "messageSent:" + paramObject, Toast.LENGTH_SHORT).show();
}
public void sessionClosed(IoSession paramIoSession)
throws Exception {
}
public void sessionCreated(IoSession paramIoSession)
throws Exception {
}
public void sessionIdle(IoSession paramIoSession, IdleStatus paramIdleStatus)
throws Exception {
}
public void sessionOpened(IoSession paramIoSession)
throws Exception {
}
}
二. client端代码:
private void sendWordSocket(String paramString) {
initSocket();
KeyWord localKeyWord = null;
if ((paramString != null) && (paramString.length() > 0) && (this.session != null) && (this.session.isConnected()))
localKeyWord = new KeyWord(paramString);
try {
if (localKeyWord == null) return;
this.session.write(new String((GsonUtils.beanToJson(localKeyWord) + "/r/n").getBytes(), "utf-8"));
return;
} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
localUnsupportedEncodingException.printStackTrace();
}
}
private void initSocket() {
try {
String ip = PreferenceUtil.getInstance(this).getString("speech_socket_url", "");
if ((ip == null) || (ip.length() == 0)) {
Toast.makeText(this, "须配置socket地址", Toast.LENGTH_SHORT).show();
return;
}
if ((this.session == null) || (!this.session.isConnected())) {
NioSocketConnector localNioSocketConnector = new NioSocketConnector();
MinaClientHanlder localMinaClientHanlder = new MinaClientHanlder();
TextLineCodecFactory localTextLineCodecFactory = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), "/r/n");
localTextLineCodecFactory.setDecoderMaxLineLength(10240);
localTextLineCodecFactory.setEncoderMaxLineLength(10240);
localNioSocketConnector.getFilterChain().addLast("textProtocol", new ProtocolCodecFilter(localTextLineCodecFactory));
localNioSocketConnector.getSessionConfig().setReadBufferSize(1048576);
InetSocketAddress localInetSocketAddress = new InetSocketAddress(ip, 8801);
localNioSocketConnector.setConnectTimeoutMillis(60000L);
localNioSocketConnector.setHandler(localMinaClientHanlder);
ConnectFuture localConnectFuture = localNioSocketConnector.connect(localInetSocketAddress);
localConnectFuture.awaitUninterruptibly();
this.session = localConnectFuture.getSession();
return;
}
} catch (final Exception localException) {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),localException.toString(),Toast.LENGTH_LONG).show();
}
});
}
}
public class MinaClientHanlder extends IoHandlerAdapter {
public MinaClientHanlder() {
}
public void messageReceived(IoSession paramIoSession, Object paramObject)
throws Exception {
System.out.println("客户端接受到了消息" + paramObject);
}
public void sessionClosed(IoSession paramIoSession) {
System.out.println("client close");
}
public void sessionOpened(IoSession paramIoSession)
throws Exception {
System.out.println("客户端登陆");
Toast.makeText(MainActivity.this, "客户端登陆", Toast.LENGTH_SHORT).show();
}
}
顺序:server通过localNioSocketAcceptor.bind(new InetSocketAddress(8801));绑定监听8801端口,设置handler回调消息,
client端连接到server端,并通过this.session.write(new String((GsonUtils.beanToJson(localKeyWord) + "/r/n").getBytes(), "utf-8"));与server端通信。其中client中的ip必须为server的ip,且端口要统一。