这个demo没有使用selector,无法使用一个单线程很好的处理多个channel的消息,性能没有使用selector高
服务端
public class Server {
public static void main(String[] args) throws Exception {
ServerSocketChannel serverS = ServerSocketChannel.open();
serverS.bind(new InetSocketAddress(8080));
ByteBuffer inB = ByteBuffer.allocate(1024);
ByteBuffer outB = ByteBuffer.allocate(1024);
while(true){
SocketChannel accept = serverS.accept();
MsgHandler.sendMsg(outB, "你好,客户端,连接建立成功", accept);
while(accept.read(inB) != -1){
String msg = MsgHandler.receiveStrMsg(inB, accept);
System.out.println(msg);
MsgHandler.sendMsg(outB, "消息处理完毕,from服务器",accept);
}
}
}
}
客户端
public class Client {
public static void main(String[] args) throws Exception {
SocketChannel clientC = SocketChannel.open();
Scanner scanner = new Scanner(System.in);
clientC.connect(new InetSocketAddress("localhost",8080));
clientC.configureBlocking(false);
ByteBuffer outB = ByteBuffer.allocate(1024);
ByteBuffer inB = ByteBuffer.allocate(1024);
while(true){
while(clientC.read(inB) > 0){
System.out.println(MsgHandler.receiveStrMsg(inB, clientC));
}
String msg = scanner.next();
MsgHandler.sendMsg(outB, msg, clientC);
if(msg.equals("exit")){
clientC.close();
return;
}
}
}
}
消息处理类
public class MsgHandler {
public static void sendMsg (ByteBuffer outB, String msg, SocketChannel channel){
try {
outB.put(msg.getBytes("UTF-8"));
outB.flip();
while(outB.hasRemaining()){
channel.write(outB);
}
}catch (Exception e){
e.printStackTrace();
}finally {
outB.clear();
}
}
public static String receiveStrMsg(ByteBuffer inB, SocketChannel channel){
List<Byte> bList = new ArrayList<>();
String msg = null;
try {
inB.flip();
while(inB.hasRemaining()){
bList.add(inB.get());
}
byte[] bytes = new byte[bList.size()];
for(int i = 0;i < bList.size();i++){
bytes[i] = bList.get(i);
}
msg = new String(bytes, "UTF-8");
}
catch (Exception e){
e.printStackTrace();
}finally {
inB.clear();
return msg;
}
}
}