直接上代码
//服务端
import java.io.IOException;
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 org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import com.haople.manager.lockset.socket.util.DataUtil;
public class SocketServer {
private static final Logger logger=Logger.getLogger(SocketServer.class);
@Value("${server_addr}")
private String serverAddr;
@Value("${socket_port}")
private Integer port;
private Selector selector;
public void start() throws IOException {
logger.info("正在启动socket服务");
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(serverAddr,port)); // 绑定本地端口
serverSocketChannel.configureBlocking(false); // 设置通道为非阻塞
selector=Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
logger.info("启动socket服务--[ "+serverAddr+" : "+port+" ]--成功!");
while(true){
selector.select();
Iterator<SelectionKey> ite=selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey key = ite.next();
ite.remove();
if (key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
SocketChannel sc = ssc.accept();
logger.info("客户端机子的地址是 "+sc.socket().getRemoteSocketAddress()+ " 客户端机机子的端口号是 "+ sc.socket().getLocalPort());
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
}
else if(key.isReadable()){
recive(key);
}
}
}
}
public void recive(SelectionKey key){
SocketChannel sc = (SocketChannel) key.channel();
try {
ByteBuffer dst=ByteBuffer.allocate(5*1024);//5K
dst.clear();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
readBuffer.clear();
while(true){
int bytesRead=sc.read(readBuffer);
if(bytesRead>0){
readBuffer.flip();
dst.put(readBuffer);
readBuffer.clear();
}else{
break;
}
}
dst.flip();
String request=new String(dst.array());
logger.info("接收数据:"+request);
String response="hello word";
ByteBuffer writeBuffer=ByteBuffer.wrap(DataUtil.encodeUTF(response));
sc.write(writeBuffer);
} catch (IOException e) {
logger.info("--处理异常--",e);
}
}
}
客户端:
方法:
public void start() {
try {
SocketChannel socketChannel=SocketChannel.open();
boolean flag=socketChannel.connect(new InetSocketAddress("127.0.0.1",8888));
String res="hello service";
System.err.println("发送-:"+res);
byte[] bs1=DataUtil.encodeUTF(res);
ByteBuffer writeBuffer=ByteBuffer.wrap(bs1);
socketChannel.write(writeBuffer);
ByteBuffer buffer = ByteBuffer.allocate(100);
socketChannel.read(buffer);
byte[] data = buffer.array();
String message = new String(data);
System.out.println("recevie message from server:, size:" + buffer.position() + " msg: " + message);
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}