初识Mina框架


Mina框架简单使用


需通过Build Path导入

mina-core-x.x.x.jar

slf4j-api-x.x.x.jar


MyServerHandler

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class MyServerHandler extends IoHandlerAdapter {

	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		System.out.println("exceptionCaught");
	}

	public void messageReceived(IoSession session, Object message)
			throws Exception {
		String s = (String) message;
		System.out.println("messageReceived:" + s);
		session.write("server reply:" + s);
	}

	public void messageSent(IoSession session, Object message) throws Exception {
		System.out.println("messageSent");
	}

	public void sessionClosed(IoSession session) throws Exception {
		System.out.println("sessionClosed");
	}

	public void sessionCreated(IoSession session) throws Exception {
		System.out.println("sessionCreated");
	}

	// 会持续不断地一直被调用
	// 一般用于服务器检测客户端是否掉线 心跳机制
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		System.out.println("sessionIdle");
	}

	public void sessionOpened(IoSession session) throws Exception {
		System.out.println("sessionOpened");
	}

}



MinaServer

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MinaServer {

	public static void main(String[] args) {
		try {
			// 1.
			NioSocketAcceptor acceptor = new NioSocketAcceptor();
			// 2.
			acceptor.setHandler(new MyServerHandler());
			// 3.
			acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory())); // 二进制数据到对象转化
			acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 5); // 5s
			// 4.
			acceptor.bind(new InetSocketAddress(9898));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}



SocketClient

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class SocketClient {

	public static void main(String[] args) {
		SocketClient client = new SocketClient();
		client.start();
	}
	
	public void start() {
		BufferedReader inputReader = null;
		// 从socket读取
		BufferedReader reader = null;
		BufferedWriter writer = null;
		Socket socket = null;
		// Alt + Shift + z    try...catch等快捷键
		// 从Console读取内容
		try {
			socket = new Socket("127.0.0.1", 9898);
			// 用于读取服务器返回的数据
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// 从socket进行写入
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			inputReader = new BufferedReader(new InputStreamReader(System.in));
			startServerReplyListener(reader);
			String inputContent;
			while (!(inputContent = inputReader.readLine()).equals("bye")) {
				writer.write(inputContent + "\n");
				writer.flush();
//				System.out.println(inputContent);
//				// 服务器返回的数据
//				String response = reader.readLine();
//				System.out.println(response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
				writer.close();
				inputReader.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 接收服务器消息的监听器
	 * 需要一直运行
	 */
	public void startServerReplyListener(final BufferedReader reader) {
		new Thread(new Runnable() {
			public void run() {
				try {
					String response;
					while ((response = reader.readLine()) != null) {
						System.out.println(response);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

}





你可能感兴趣的:(Socket,Mina)