纯自用
server端:
import java.io.ByteArrayOutputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.HexUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class SGServer {
public static void main(String[] args) {
SGServer server = new SGServer();
server.run();
}
private int port = 8080;
private ServerSocketChannel ssc = null;
private Selector selector = null;
public void init() throws Exception {
if (null == ssc) {
ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress(port));
ssc.configureBlocking(false);
selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
}
}
public void run() {
SelectionKey key = null;
try {
this.init();
while (true) {
if (selector.select(3000) == 0) {
continue;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iter = selectionKeys.iterator();
while (iter.hasNext()) {
key = iter.next();
iter.remove();
if (key.isValid() && key.isAcceptable()) {
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
System.out.println("有一个客户端连接成功,hashCode = " + sc.hashCode());
sc.register(selector, SelectionKey.OP_READ);
}
if (key.isValid() && key.isReadable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buff = ByteBuffer.allocate(1024);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (sc.read(buff) > 0) {
int pos = buff.position();
if (pos < buff.capacity()) {
baos.write(ArrayUtil.sub(buff.array(), 0, pos));
} else {
baos.write(buff.array());
}
}
String hex = HexUtil.encodeHexStr(baos.toByteArray());
System.out.println("客户端发送:" + hex);
// TODO 其他业务处理,并返回data
byte[] data = {};
data = "qwertyuiopasdfghjklzxcvbnm".getBytes();
sc.register(selector, SelectionKey.OP_WRITE);
key.attach(ByteBuffer.wrap(data));
}
if (key.isValid() && key.isWritable()) {
SocketChannel sc = (SocketChannel) key.channel();
ByteBuffer buff = (ByteBuffer) key.attachment();
if (null != buff) {
sc.write(buff);
}
sc.close();
}
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
}
}
}
client端:
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.HexUtil;
public class SGClient {
public static void main(String[] args) {
SGClient client = new SGClient();
byte[] msg = "1234567890abcdef1234567890abcdef".getBytes();
client.sendMsg(msg);
}
private String host = "127.0.0.1";
private int port = 8080;
public void sendMsg(byte[] msg) {
// 1、创建客户端Socket,指定服务器地址和端口
try {
Socket socket = new Socket("localhost", 10020);
// 2、获取输出流,向服务器端发送信息
OutputStream os = socket.getOutputStream();// 获取字节输出流
String str = "https://www.jit.com.cn";
os.write(str.getBytes("UTF-8"));
byte[] buff = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = socket.getInputStream();
int pos = 0;
while ((pos = is.read(buff)) > 0) {
if (pos < buff.length) {
baos.write(ArrayUtil.sub(buff, 0, pos));
} else {
baos.write(buff);
}
}
String hex = HexUtil.encodeHexStr(baos.toByteArray());
System.out.println("服务返回:" + hex);
// 3、关闭资源
os.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMsg1(byte[] msg) {
SocketChannel sc = null;
try {
sc = SocketChannel.open();
sc.connect(new InetSocketAddress(host, port));
sc.configureBlocking(true);
sc.write(ByteBuffer.wrap(msg));
ByteBuffer buff = ByteBuffer.allocate(1024);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (sc.read(buff) > 0) {
byte[] data = buff.array();
int pos = buff.position();
if (pos < buff.capacity()) {
data = ArrayUtil.sub(data, 0, pos);
}
baos.write(data);
}
String hex = HexUtil.encodeHexStr(baos.toByteArray());
System.out.println("服务返回:" + hex);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != sc) {
try {
sc.close();
sc = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}