客户端非阻塞式通信(Java Socket Channel)

服务端代码(阻塞式):

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

/**
 * 服务器端阻塞式IO(Java ServerSocket)
 * @author Bright Lee
 */
public class ServerSocketTest {

	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream in = null;
		try {
			serverSocket = new ServerSocket(6666);
			socket = serverSocket.accept();
			
			SocketAddress clientAddress = socket.getRemoteSocketAddress();
			System.out.println("有客户端连接:" + clientAddress);
			
			in = socket.getInputStream();
			
			int value = -1;
			
			while ((value = in.read()) != -1) {
				char ch = (char) value;
				System.out.print(ch);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(serverSocket, socket, in);
		}
	}
	
	private static void close(ServerSocket serverSocket, Socket socket, InputStream in) {
		try {
			if (in != null) {
				in.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (socket != null) {
				socket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (serverSocket != null) {
				serverSocket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

客户端代码(非阻塞式):

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 客户端非阻塞式IO(Java SocketChannel)
 * @author Bright Lee
 */
public class SocketChannelTest {

	public static void main(String[] args) {
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		SocketChannel socketChannel = null;
		try {
			socketChannel = SocketChannel.open();
			socketChannel.configureBlocking(false);
			socketChannel.connect(new InetSocketAddress("127.0.0.1", 6666));
			
			if (socketChannel.finishConnect()) {
				String info = "I'm a client! My number is " + System.currentTimeMillis();
				buffer.clear();
				buffer.put(info.getBytes("UTF-8"));
				buffer.flip();
				while (buffer.hasRemaining()) {
					socketChannel.write(buffer);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (socketChannel != null) {
					socketChannel.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}

先运行服务端代码(ServerSocketTest.java),再运行客户端代码(SocketChannelTest.java),服务端打印信息如下:
有客户端连接:/127.0.0.1:51564
I’m a client! My number is 1547276873269

你可能感兴趣的:(Core,Java)