Java--NIO(三)

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值