服务器端(非阻塞):
package org.snake.socket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
private static final int DEFAULT_PORT = 12346; // 默认端口号
private static ExecutorService exec = Executors.newFixedThreadPool(10);
private static final String HELLO = "Hello,Client";
public static void main(String[] args) throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open(); // 开启一个 server-socket通道
ssc.configureBlocking(false); // 设置该通道为非阻塞模式
ServerSocket ss = ssc.socket(); // 取得与该通道关联的server socket
InetSocketAddress ina = new InetSocketAddress(DEFAULT_PORT); // 用给定的端口号创建一个socket-address
ss.bind(ina); // 将该通道绑定到指定的地址
final ByteBuffer buff = ByteBuffer.allocate(128); // 分配一个容量为128字节的缓冲区
while(true) {
final SocketChannel sc = ssc.accept(); // 因为该通道为非阻塞模式,所以会立即返回,返回值可能为null
if(sc == null) {
// System.out.println("当前没有连接进入");
}
else {
// 另起一个线程来处理客户请求
exec.execute(new Runnable() {
@Override
public void run() {
// 写向客户端
buff.clear();
buff.put(HELLO.getBytes());
buff.flip();
try {
sc.write(buff);
} catch (IOException e) {
e.printStackTrace();
}
//读取客户端
buff.clear();
try {
sc.read(buff);
} catch (IOException e) {
e.printStackTrace();
}
buff.flip();
while(buff.hasRemaining()) {
System.out.print((char)buff.get());
}
System.out.println();
}
});
}
}
}
}
客户端(阻塞式):
package org.snake.socket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class Client {
private static final int DEFAULT_PORT = 12346;
private static final String DEFAULT_IP = "localhost";
private static final String HELLO = "Hello,Server";
public static void main(String[] args) throws IOException{
SocketChannel sc = SocketChannel.open();
InetSocketAddress ina = new InetSocketAddress(DEFAULT_IP, DEFAULT_PORT);
sc.connect(ina); // 该方法会阻塞,因为该通道为阻塞模式
//写到服务器
ByteBuffer buff = ByteBuffer.allocate(128);
buff.put(HELLO.getBytes());
buff.flip();
sc.write(buff);
//读取服务器
buff.clear();
sc.read(buff);
buff.flip();
while(buff.hasRemaining()) {
System.out.print((char)buff.get());
}
sc.close(); //关闭通道
}
}