//BIO服務端
public class BIOServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket();
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9001);
serverSocket.bind(address);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(socket.getLocalAddress().getHostAddress() + "連接配接了");
InputStream inputStream = null;
try {
inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String str = null;
str = reader.readLine();
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
//BIO用戶端
public class BIOClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 9001);
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
BufferedWriter writer = new BufferedWriter(outputStreamWriter);
String str = "你好";
writer.write(str);
//重新整理輸入流
writer.flush();
//關閉socket的輸出流
socket.shutdownOutput();
} catch (Exception e) {
e.printStackTrace();
}
}
//NIO服務端
public class NIOServer {
/**
* 選擇器
*/
private Selector selector;
/**
* 通道
*/
ServerSocketChannel serverSocketChannel;
public void initServer(int port) throws IOException
{
//打開一個通道
serverSocketChannel = ServerSocketChannel.open();
//通道設定非阻塞
serverSocketChannel.configureBlocking(false);
//綁定端口号
serverSocketChannel.socket().bind(new InetSocketAddress("0.0.0.0", port));
//注冊
this.selector = Selector.open();
//先注冊事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}
public void listen() throws IOException
{
System.out.println("server started succeed!");
while (true)
{
//阻塞到至少有一個就緒通道
selector.select();
Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
while (ite.hasNext())
{
SelectionKey key = ite.next();
if (key.isAcceptable())
{
//接收新請求,并建立新通道
SocketChannel channel = serverSocketChannel.accept();
channel.configureBlocking(false);
//通道注冊可讀事件
channel.register(selector, SelectionKey.OP_READ);
}
else if (key.isReadable())
{
recvAndReply(key);
}
ite.remove();
}
}
}
public void recvAndReply(SelectionKey key)
{
SocketChannel channel = (SocketChannel) key.channel();
try {
ByteBuffer buffer = ByteBuffer.allocate(256);
int i = channel.read(buffer);
if (i != -1) {
String msg = new String(buffer.array()).trim();
System.out.println(new Date() + ",NIO server received message = " + msg);
System.out.println(new Date() + ",NIO server reply = " + msg);
//通道寫入資料
channel.write(ByteBuffer.wrap(msg.getBytes()));
} else {
//多線程處理業務
channel.close();
}
}catch (IOException e) {
e.printStackTrace();
try {
channel.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException
{
NIOServer server = new NIOServer();
server.initServer(8001);
server.listen();
}
//NIO用戶端
public class NIOClient {
/**
* 通道
*/
SocketChannel channel;
public void initClient(String host, int port) throws IOException
{
//構造socket連接配接
InetSocketAddress servAddr = new InetSocketAddress(host, port);
//通過通道,打開連接配接
this.channel = SocketChannel.open(servAddr);
}
public void sendAndRecv(String words) throws IOException {
byte[] msg = new String(words).getBytes();
ByteBuffer buffer = ByteBuffer.wrap(msg);
System.out.println(new Date() + ",Client sending: " + words);
//通道寫資料
channel.write(buffer);
buffer.clear();
//阻塞,通道讀資料
channel.read(buffer);
System.out.println(new Date() + ",Client received: " + new String(buffer.array()).trim());
}
public void close() throws IOException {
channel.close();
}
public static void main(String[] args) throws IOException {
NIOClient client = new NIOClient();
try {
client.initClient("localhost", 8001);
Random random = new Random(10000000);
while (true) {
client.sendAndRecv(random.nextInt() + ",I am a client");
}
} catch (Exception e) {
e.printStackTrace();
client.close();
}
}