|
那么好,我们开始进行一下简单的测试,在测试的时候为了方便客户端我使用的是阻塞式的io,因为主要是为了测试服务端,所以对客户端的程序我没有进行特意的编写,下面先展示一下如何启动服务端程序
package com.wangwenjun.nio.frame;public class ServerTest {public static void main(String[] args) throws Exception {NioServerListener serverListener = new NioServerListener(8888);serverListener.setMessageHandler(new MessageHander());serverListener.setCombinate(new MessageCombinateImpl());serverListener.start();}}
可以看出来经过封装之后服务端的使用显得很轻巧和便捷,接下来的代码是客户端的代码
package com.wangwenjun.nio;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import com.neusoft.nio.frame.ByteUtils;public class ClientTest {private final static String str="The Apache Software Foundation provides support for the Apache community of open-source software projects. The Apache projects are characterized by";public static void main(String[] args) throws UnknownHostException, IOException {Socket socket = new Socket("localhost",8888);InputStream is=socket.getInputStream();OutputStream os = socket.getOutputStream();Thread t = new Thread(new ClientRecieve(is));t.start();for(int i=0;i<3000;i++){int len = str.getBytes().length+4;byte[] lenB = ByteUtils.int2bytes(len);byte[] bodys = str.getBytes();byte[] b=new byte[len];System.arraycopy(lenB, 0, b, 0, 4);System.arraycopy(bodys, 0, b, 4, str.getBytes().length);os.write(b);}}}class ClientRecieve implements Runnable{private Logger log = LoggerFactory.getLogger(this.getClass());private InputStream is = null;public ClientRecieve(InputStream is){this.is =is;}public void run() {while(true){byte[] b = new byte[4];try {int len=is.read(b);byte[] real = new byte[len];System.arraycopy(b, 0, real, 0, len);int resp=ByteUtils.bytes2int(real,4);log.info("resp:---->"+resp);} catch (IOException e) {e.printStackTrace();} catch (Throwable e) {e.printStackTrace();}}}}
在客户端我们发送了一个一百多个字节的字符串,我测试的时候发送的是500多个字节的字符串,经过3000条的测试,每秒的速度大约能处理3000条以上(500多个字节的消息) |
|