Socket—NIO
NIO—TCP—Client & BIO–TCP—Server
NIO—TCP—Client
public class SocketNio {
public static void main(String[] args) throws Exception {
Client nioClient = new Client();
nioClient.init();
}
}
@Slf4j
class Client {
public void init() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
SocketAddress remote = new InetSocketAddress("127.0.0.1", 8080);
socketChannel.connect(remote);
log.info("nio客户端启动完成...");
if (socketChannel.finishConnect()) {
int i = 0;
while (true) {
TimeUnit.SECONDS.sleep(1);
String info = "I'm " + i++ + "-th information from client";
buffer.clear();
buffer.put(info.getBytes());
buffer.flip();
while (buffer.hasRemaining()) {
log.info("缓冲区内容: {}", buffer);
socketChannel.write(buffer);
}
}
}
} catch (Exception e) {
log.error("client init Exception", e);
} finally {
if (socketChannel != null) {
try {
socketChannel.close();
} catch (IOException e) {
log.error("client socketChannel close Exception", e);
}
}
}
}
}
BIO–TCP—Server
public class T1 {
public static void main(String[] args) throws Exception {
Server.init();
}
}
@Slf4j
class Server {
public static void init() {
ServerSocket serverSocket = null;
InputStream in = null;
try {
serverSocket = new ServerSocket(8080);
int recvMsgSize = 0;
byte[] recvBuf = new byte[1024];
log.info("服务端启动完成...");
while (true) {
Socket clntSocket = serverSocket.accept();
SocketAddress clientAddress = clntSocket.getRemoteSocketAddress();
log.info("Handling client at {}", clientAddress);
in = clntSocket.getInputStream();
while ((recvMsgSize = in.read(recvBuf)) != -1) {
byte[] temp = new byte[recvMsgSize];
System.arraycopy(recvBuf, 0, temp, 0, recvMsgSize);
log.info("服务端收到消息:{}", new String(temp));
}
}
} catch (Exception e) {
log.error("server init Exception", e);
} finally {
try {
if (serverSocket != null) {
serverSocket.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
SocketChannel的用法
//打开连接
socketChannel = SocketChannel.open();
//非阻塞模式
socketChannel.configureBlocking(false);
//连接地址
SocketAddress remote = new InetSocketAddress("127.0.0.1", 8080);
//创建连接
socketChannel.connect(remote);
//关闭 SocketChannel
socketChannel.close();
- connect()
如果SocketChannel在非阻塞模式下,此时调用connect(),该方法可能在连接建立之前就返回了。为了确定连接是否建立,可以调用finishConnect()的方法。像这样:
socketChannel.connect(remote);
if (socketChannel.finishConnect()) {
// do something...
...
}
- 写入数据
String info = "I'm " + i++ + "-th information from client";
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.clear();
buffer.put(info.getBytes());
buffer.flip();
while (buffer.hasRemaining()) {
socketChannel.write(buffer);
}
- 读取数据
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = socketChannel.read(buf);