nio/mina(四)客户端socket与mina服务端通信

客户端socket传对象给mina服务端暂时不通,可能跟下面传中文字符串有些类似.

应该和mina端过滤器的相关设置有关.

服务端:

1 MinaServer.java

package com.nafio.server;  
      
    import java.io.IOException;  
    import java.net.InetSocketAddress;  
      
    import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;  
    import org.apache.mina.filter.codec.ProtocolCodecFilter;  
    import org.apache.mina.filter.codec.textline.TextLineCodecFactory;  
    import org.apache.mina.transport.socket.SocketAcceptor;  
    import org.apache.mina.transport.socket.nio.NioSocketAcceptor;  
      
    public class MinaServer {      
        private static MinaServer minaServer = null;  
        //创建一个非阻塞的Server端Socket  
        private SocketAcceptor acceptor = new NioSocketAcceptor();  
        //创建接收数据的过滤器  
        private DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();          
        private int bindPort = 8888;  
          
        //单例  
        public static MinaServer getInstances() {      
            if (null == minaServer) {                 
                minaServer = new MinaServer();      
            }              
            return minaServer;      
        }          
        private MinaServer() {              
            //设定这个过滤器将按对象读取数据  
              
            //单例模式----------------------------------------  
    //      chain.addLast("myChin", new ProtocolCodecFilter(      
    //              new ObjectSerializationCodecFactory()));   
            //设定服务器端的消息处理器:一个MinaServerHandler对象,  
    //      acceptor.setHandler(ServerHandler.getInstances());     
              
              
            //非单例模式---------------------------------------  
            //接收文字  
            chain.addLast("myChin", new ProtocolCodecFilter(      
                    new TextLineCodecFactory()));   
            //接收对象  
    //      chain.addLast("myChin", new ProtocolCodecFilter(      
    //              new ObjectSerializationCodecFactory()));   
              
              
            acceptor.setHandler(new ServerHandler());  
            try {  
                //绑定端口,启动服务器  
                acceptor.bind(new InetSocketAddress(bindPort));  
                  
            } catch (IOException e) {                  
                e.printStackTrace();      
            }   
            System.out.println("服务端:监听端口--->" + bindPort);  
        }      
        public static void main(String[] args) throws Exception {      
            MinaServer.getInstances();   
            //new MinaServer();  
        }      
    }

2 ServerHandler.java

package com.nafio.server;  
      
    import org.apache.mina.core.filterchain.IoFilterAdapter;  
    import org.apache.mina.core.service.IoHandler;  
    import org.apache.mina.core.service.IoHandlerAdapter;  
    import org.apache.mina.core.session.IdleStatus;  
    import org.apache.mina.core.session.IoSession;  
      
    import com.nafio.obj.TransferObj;  
    //下面两种写法应该等同,不确定?  
    //public class ServerHandler extends IoHandlerAdapter {    
    public class ServerHandler extends IoFilterAdapter implements IoHandler {      
        private static ServerHandler samplMinaServerHandler = null;          
        public static ServerHandler getInstances() {  
            if (null == samplMinaServerHandler) {      
                samplMinaServerHandler = new ServerHandler();  
            }      
            return samplMinaServerHandler;          
        }      
        public ServerHandler() {      
        }      
        public void sessionOpened(IoSession session) throws Exception {  
            System.out.println("服务端:会话打开");  
        }      
        public void sessionClosed(IoSession session) {  
      
        }    
          
        public void messageReceived(IoSession session, Object message)throws Exception {  
            //接收字符串  
            String str = (String)message;  
            System.out.println("服务端:收到客户端发来的信息--->"+str);  
            //System.out.println("服务端:收到信息");  
            //接收对象  
    //      if (message instanceof TransferObj) {  
    //          TransferObj obj = (TransferObj) message;      
    //          System.out.println("服务端:收到客户端数据--->"+obj.getDate());+      
    //      }           
        }      
        public void exceptionCaught(IoSession arg0, Throwable arg1)throws Exception {          
        }          
        public void messageSent(IoSession arg0, Object arg1) throws Exception {      
              
        }      
        public void sessionCreated(IoSession arg0) throws Exception {  
            System.out.println("服务端:会话创建");  
        }          
        public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {   
              
        }      
    }

socket客户端

SocketClient.java

package com.nafio.socketclient;  
      
    import java.io.DataInputStream;  
    import java.io.DataOutputStream;  
    import java.io.IOException;  
    import java.io.ObjectOutputStream;  
    import java.net.Socket;  
    import com.nafio.obj.TransferObj;  
      
      
    public class SocketClient {  
          
        private Socket s;  
        private DataOutputStream out;  
        private DataInputStream in;  
        public SocketClient() throws IOException {  
        }  
      
      
        public static void main(String[] args) throws Exception {  
            SocketClient c = new SocketClient();  
            c.talk();  
        }  
    //  发送对象  
    //  ObjectOutputStream oos;  
    //  TransferObj obj;  
        public void sendMessage(Socket s) {  
            try {  
                  
                //socket传字符串  
                out = new DataOutputStream(s.getOutputStream());  
                byte[] bt="中文\n".getBytes();  
                out.write(bt);  
                out.writeBytes("nafio_date\n");  
                //out.writeUTF("中文\n");//by nafio这么写不行  
                  
                //socket传对象  
    //          oos = new ObjectOutputStream(s.getOutputStream());  
    //          obj=new TransferObj();  
    //          obj.setDate("socketDateToMina");  
    //          oos.writeObject(obj);  
    //          oos.flush();  
                  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
      
        }  
      
        public void receiveMessage(Socket s) {  
            try {  
                in = new DataInputStream(s.getInputStream());  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
      
        public void talk() throws Exception {  
            /*while (true)*/ {  
                try {  
                    //发送对象  
                    //oos.close();  
                    s = new Socket("localhost", 8888);  
                    System.out.println("客户端:发送信息");  
                    sendMessage(s);  
                    System.out.println("发送信息完毕!");  
                    //发字符串  
                    //receiveMessage(s);  
                    out.close();  
                    //in.close();  
                }  
                catch(Exception e){  
                    e.printStackTrace();  
                }  
                finally {  
                    try{  
                        if(s!=null)s.close();  //断开连接  
                    }catch (IOException e) {e.printStackTrace();}  
                }  
            }  
        }  
    }

相关推荐