代码拉取完成,页面将自动刷新
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();
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。