java nio socket 服务端开发 demo

直接上代码

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import com.haople.manager.lockset.socket.service.ManagerService;


public class SocketServer {
	private static final Logger logger=Logger.getLogger(SocketServer.class);
	

	@Value("${server_addr}")
	private String serverAddr;
	@Value("${socket_port}")
	private Integer port;
	
	public void start() {
		try {
			logger.info("正在启动socket服务");
			ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.socket().bind(new InetSocketAddress(serverAddr,port)); // 绑定本地端口
			serverSocketChannel.configureBlocking(false); // 设置通道为非阻塞
			logger.info("启动socket服务--[ "+serverAddr+" : "+port+" ]--成功!");
			while(true){
				SocketChannel socketChannel=serverSocketChannel.accept();
				if(socketChannel!=null){
					socketChannel.configureBlocking(false);
					new Thread(new Processor(socketChannel)).start();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	class Processor implements Runnable{
		private SocketChannel socketChannel;
		public Processor(SocketChannel socketChannel) {
			this.socketChannel=socketChannel;
		}
		@Override
		public void run() {
			try {
				StringBuffer stringBuffer=new StringBuffer();
				ByteBuffer readBuffer = ByteBuffer.allocate(1024);
				readBuffer.clear();
				while(true){
					int bytesRead=socketChannel.read(readBuffer);
					if(bytesRead>0){
						readBuffer.flip();
						stringBuffer.append(new String(readBuffer.array(),"UTF-8"));
						readBuffer.clear();
					}else{
						break;
					}
				}
				if(!StringUtils.isEmpty(stringBuffer.toString())){ //获取请求的全部数据
					String response="hello world";
					logger.info("响应数据:"+response);
					ByteBuffer writeBuffer=ByteBuffer.wrap(response.getBytes("UTF-8"));
					socketChannel.write(writeBuffer);
					
				}
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					socketChannel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
}



你可能感兴趣的:(java,socket,nio,demo,服务端开发)