1 Star 2 Fork 1

peipeihh / blog

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ChannelServer.java 1.95 KB
一键复制 编辑 原始数据 按行查看 历史
huangyinhuang 提交于 2018-02-06 13:59 . 添加java nio的演示项目
package channel;
import util.Logger;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* Created by huangyinhuang on 1/31/2018.
*/
public class ChannelServer {
public static void main(String[] args) throws Exception {
// please note: configure channel blocking state as false
Logger.info("start the server.");
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
ServerSocket serverSocket = server.socket();
serverSocket.bind(new InetSocketAddress(9000));
int count = 0;
while (true) {
// please note: server.accept() will not block current thread
Logger.info("try to connect new client...");
SocketChannel channel = server.accept();
if (channel == null) {
Logger.info("waiting for new client, count = " + count++);
Thread.sleep(5000);
} else {
Logger.info("connected with client...");
Logger.printClientInfo(channel);
ByteBuffer clientMsg = ByteBuffer.allocate(1024);
channel.read(clientMsg);
clientMsg.flip();
if (clientMsg.hasRemaining()) {
// print messages from client
byte[] msgBytes = new byte[clientMsg.remaining()];
clientMsg.get(msgBytes);
Logger.printNewMessage(new String(msgBytes).trim());
}
clientMsg.clear();
// prepare the message
ByteBuffer replyMsg = ByteBuffer.wrap("Hello client, this is channel server.".getBytes());
channel.write(replyMsg);
// close the client, wait for next client connection
channel.close();
}
}
}
}
1
https://gitee.com/pphh/blog.git
git@gitee.com:pphh/blog.git
pphh
blog
blog
master

搜索帮助