Netty 通过Map管理用户Channel

有时候我们需要绑定用户id,让他们可以通过id与对方进行通信

通过Map实现一个简单的连接池

import io.netty.channel.socket.SocketChannel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class GatewayService{
    private static Map map = new ConcurrentHashMap();

    public static void addGatewayChannel(String id, SocketChannel gateway_channel){
    map.put(id,gateway_channel);
    }

    public static Map getChannels(){
        return map;
    }

    public static SocketChannel getGatewayChannel(String id){
        return (SocketChannel)map.get(id);
    }

    public static void removeGatewayChannel(String id){
        map.remove(id);
    }
}

 

通过@MultipartConfig 实现文件上传

  • 前端
        <form action="/userCodeDataUploadPic" method="post" enctype="multipart/form-data">
            <input type="file" name="file">
            <input type="submit" name="upload" value="上传">
        </form>
  • 后端
package javaee.servlet;
import …………
//设置访问活着调用这个Servlet的路径
@WebServlet("/UpLoad")
//说明该Servlet处理的是multipart/form-data类型的请求
@MultipartConfig
public class UpLoad extends HttpServlet{
	private static final long serialVersionUID = 1L;
	public UpLoad(){
		super();
	}
	protected void doGet(HttpServletRequest request,HttpServletResponse response)
		throws ServletException,IOException{
		this.doPost(request, response);
	}
	protected void doPost(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException{
		//说明输入的请求信息采用UTF-8编码方式
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		//Servlet3.0中新引入的方法,用来处理multipart/form-data类型编码的表单
		Part part = request.getPart("file");
		//获取HTTP头信息headerInfo=(form-data; name="file" filename="文件名")
		String headerInfo = part.getHeader("content-disposition");
		//从HTTP头信息中获取文件名fileName=(文件名)
		String fileName = headerInfo.substring(headerInfo.lastIndexOf("=") + 2, headerInfo.length() - 1);
		//获得存储上传文件的文件夹路径
		String fileSavingFolder = this.getServletContext().getRealPath("/UpLoad");
		//获得存储上传文件的完整路径(文件夹路径+文件名)
		//文件夹位置固定,文件夹采用与上传文件的原始名字相同
		String fileSavingPath = fileSavingFolder + File.separator + fileName;
		//如果存储上传文件的文件夹不存在,则创建文件夹
		File f = new File(fileSavingFolder + File.separator);
		if(!f.exists()){
			f.mkdirs();
		}
		//将上传的文件内容写入服务器文件中
		part.write(fileSavingPath);
		//输出上传成功信息
		out.println("文件上传成功~!");
	}
}