Mina TCP服务端客户端 示例

来源:互联网 发布:淘宝文案策划怎么样 编辑:程序博客网 时间:2024/06/06 12:21

服务端代码:

package minaT3;import java.io.IOException;import java.net.InetSocketAddress;import org.apache.mina.core.buffer.IoBuffer;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;/** * @说明 Mina TCP 服务端 * @author administrator *  */public class MinaTcpServer extends IoHandlerAdapter {public static final int PORT = 18567;public MinaTcpServer() throws IOException {NioSocketAcceptor acceptor = new NioSocketAcceptor();acceptor.setHandler(this);acceptor.bind(new InetSocketAddress(PORT));System.out.println("TCP服务启动,端口:" + PORT);}public static void main(String[] args) throws IOException {new MinaTcpServer();}@Overridepublic void messageReceived(IoSession session, Object message) {IoBuffer bbuf = (IoBuffer) message;byte[] byten = new byte[bbuf.limit()];bbuf.get(byten, bbuf.position(), bbuf.limit());System.out.println("收到消息:" + ByteAndStr16.Bytes2HexString(byten));byte[] bts = new byte[10];for (int i = 0; i < 10; i++) {bts[i] = (byte) i;}IoBuffer buffer = IoBuffer.allocate(10);buffer.put(bts);buffer.flip();session.write(buffer);// // 拿到所有的客户端Session// Collection<IoSession> sessions =// session.getService().getManagedSessions().values();// // 向所有客户端发送数据// for (IoSession sess : sessions) {// sess.write(buffer);// }}@Overridepublic void sessionClosed(IoSession session) {System.out.println("会话关闭");}@Overridepublic void exceptionCaught(IoSession session, Throwable cause)throws Exception {System.out.println("会话异常");super.exceptionCaught(session, cause);}@Overridepublic void messageSent(IoSession session, Object message) throws Exception {System.out.println("服务端消息发送");super.messageSent(session, message);}@Overridepublic void sessionCreated(IoSession session) throws Exception {System.out.println("会话创建");super.sessionCreated(session);}@Overridepublic void sessionIdle(IoSession session, IdleStatus idlestatus)throws Exception {System.out.println("会话休眠");super.sessionIdle(session, idlestatus);}@Overridepublic void sessionOpened(IoSession session) throws Exception {System.out.println("会话打开");super.sessionOpened(session);}}

服务端建立端口监听后,收到消息后进入messageReceived()方法,示例处理是打印该消息,然后组装了一个0-9的数据返回回去

注意,即使使用的是Mina,仍需做分包、粘包,等处理,例如有时一条数据不是一次发过来的


客户端程序:

package minaT3;import java.net.InetSocketAddress;import org.apache.mina.core.buffer.IoBuffer;import org.apache.mina.core.future.ConnectFuture;import org.apache.mina.core.service.IoConnector;import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;import org.apache.mina.transport.socket.nio.NioSocketConnector;public class MinaTcpClient extends IoHandlerAdapter {private IoConnector connector;private static IoSession session;public MinaTcpClient() {connector = new NioSocketConnector();connector.setHandler(this);ConnectFuture connectFuture = connector.connect(new InetSocketAddress("localhost", MinaTcpServer.PORT));connectFuture.awaitUninterruptibly();session = connectFuture.getSession();System.out.println("TCP 客户端启动");}public static void main(String[] args) throws InterruptedException {MinaTcpClient client = new MinaTcpClient();for (int i = 0; i < 2; i++) { // 发送两遍  byte[] bts = new byte[20];for (int j = 0; j < 20; j++) {bts[j] = (byte) j;}IoBuffer buffer = IoBuffer.allocate(20);//自动扩容buffer.setAutoExpand(true);//自动收缩buffer.setAutoShrink(true);buffer.put(bts);buffer.flip();session.write(buffer);Thread.sleep(2000);} // 关闭会话,待所有线程处理结束后client.connector.dispose();}@Overridepublic void messageReceived(IoSession session, Object message) {IoBuffer bbuf = (IoBuffer) message;byte[] byten = new byte[bbuf.limit()];bbuf.get(byten, bbuf.position(), bbuf.limit());System.out.println("客户端收到消息" + ByteAndStr16.Bytes2HexString(byten));}@Overridepublic void exceptionCaught(IoSession session, Throwable cause)throws Exception {System.out.println("客户端异常");super.exceptionCaught(session, cause);}@Overridepublic void messageSent(IoSession session, Object message) throws Exception {System.out.println("客户端消息发送");super.messageSent(session, message);}@Overridepublic void sessionClosed(IoSession session) throws Exception {System.out.println("客户端会话关闭");super.sessionClosed(session);}@Overridepublic void sessionCreated(IoSession session) throws Exception {System.out.println("客户端会话创建");super.sessionCreated(session);}@Overridepublic void sessionIdle(IoSession session, IdleStatus status)throws Exception {System.out.println("客户端会话休眠");super.sessionIdle(session, status);}@Overridepublic void sessionOpened(IoSession session) throws Exception{ System.out.println("客户端会话打开");   super.sessionOpened(session);}}

向服务端发送两次0-19的数据,收到消息后同样进入messageReceived()方法,处理同样是打印显示!

工具类代码:

package minaT3;public class ByteAndStr16 {private final static byte[] hex = "0123456789ABCDEF".getBytes();private static int parse(char c) {if (c >= 'a')return (c - 'a' + 10) & 0x0f;if (c >= 'A')return (c - 'A' + 10) & 0x0f;return (c - '0') & 0x0f;}// 从字节数组到十六进制字符串转换public static String Bytes2HexString(byte[] b) { byte[] buff = new byte[3 * b.length];          for (int i = 0; i < b.length; i++) {              buff[3 * i] = hex[(b[i] >> 4) & 0x0f];              buff[3 * i + 1] = hex[b[i] & 0x0f];              buff[3 * i + 2] = 45;          }          String re = new String(buff);          return re.replace("-", " "); }// 从十六进制字符串到字节数组转换public static byte[] HexString2Bytes(String hexstr) {hexstr = hexstr.replace(" ", "");byte[] b = new byte[hexstr.length() / 2];int j = 0;for (int i = 0; i < b.length; i++) {char c0 = hexstr.charAt(j++);char c1 = hexstr.charAt(j++);b[i] = (byte) ((parse(c0) << 4) | parse(c1));}return b;}}


打印结果:

TCP服务启动,端口:18567会话创建会话打开收到消息:00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 服务端消息发送收到消息:00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F 10 11 12 13 服务端消息发送会话关闭



客户端会话创建TCP 客户端启动客户端会话打开客户端消息发送客户端收到消息00 01 02 03 04 05 06 07 08 09 客户端消息发送客户端收到消息00 01 02 03 04 05 06 07 08 09 客户端会话关闭


0 0
原创粉丝点击