TCP服务端开发为例--web开发不同url请求为何会走不同方法
拿java的web开发为例子,相信有很多小伙伴是做j2EE开发的,htpp请求,json数据传输都是工作中经常用的,查询请求,添加请求,修改请求前端配个url,例如https://localhost/intsmaze/user/add?name=intsmaze。然后后端建立一个controler类(类上配置url映射/user),然后创建一个addUser方法(在方法上配置映射/add)。然后启动web应用,前端发送的请求就会自动走到后端的addUser方法了。
但是你知道为什么这个请求走对应的方法吗?下面让我拿我大三期间基于TCP写的服务端程序做例子来看看背后的原理吧。这个程序时一个超市管理系统,客户端使用javaSwing编写,服务端使用javaSE编写,双方通信使用TCP协议,数据存储在mysql中。完整的项目上传在github上https://github.com/intsmaze/Swing-TCP-mysql。
服务端启动类,绑定端口。
public class LoginServer { private int port=1000; private ServerSocket serversocket; private ExecutorService executorservice; private final int POOL_SIZE=1;//一个CPU线程池中工作线程的数目 public LoginServer() throws Exception { serversocket=new ServerSocket(); serversocket.bind(new InetSocketAddress("127.0.0.1",port)); executorservice=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE); //当前CPU数*1就是总线程池数目 } public void service() { while(true) { Socket socket=null; try { socket=serversocket.accept(); executorservice.execute(new Handler(socket)); }catch(IOException e) { e.printStackTrace(); } } } public static void main(String[] args) throws Exception { new LoginServer().service(); } }
路径映射方法
localhost/intsmaze/后面不同的路径就是截取对应的字符串然后调用对应的方法
public class Handler implements Runnable{ public static final int SOLDERCONNECTION=0;//售货员登录 public static final int MANAGERADDSOLDER=7;//管理员添加售货员 public static final int MANAGERDELETESOLDER=8;//管理员删除售货员 public static final int MANAGERMOIDFYSOLDER=9;//管理员修改售货员 private Socket socket; private BufferedReader bufIn=null; private BufferedWriter bufOut=null; private Connection connection=null; private PreparedStatement preparedstatement=null; private ResultSet resultset=null; public Handler(Socket socket) throws IOException { this.socket=socket; bufIn=new BufferedReader(new InputStreamReader(socket.getInputStream())); bufOut=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } public void run() { try { String line=bufIn.readLine(); //读取第一个选着功能 int i=Integer.valueOf(line); switch(i) { case SOLDERCONNECTION: solderConnection();//售货员登录0 break; case MANAGERADDSOLDER: managerAddSolder();//管理员添加售货员7 break; case MANAGERDELETESOLDER: managerDeleteSolder();//管理员删除售货员8 break; case MANAGERMOIDFYSOLDER: managerModifySolder();//管理员修改售货员9 break; } }catch(Exception e) { socketUtil.close(socket); } } public void solderConnection() throws Exception { String sr=null; //读取账号和密码 String arr[] =bufIn.readLine().split("#");; connection=JdbcUtil.getConnection(); preparedstatement=connection.prepareStatement("SELECT * FROM solder WHERE solder_number=? and solder_password=?"); preparedstatement.setString(1,arr[0]); preparedstatement.setString(2,arr[1]); resultset=preparedstatement.executeQuery(); if(resultset.next()){ bufOut.write("ok\n");//回馈查询信心 bufOut.flush(); sr=resultset.getInt(1)+"#"+resultset.getString(2)+"#"+resultset.getString(3)+"\n"; bufOut.write(sr); bufOut.flush(); } else { bufOut.write("no");//回馈查询信心 bufOut.flush(); } JdbcUtil.release(resultset, preparedstatement, connection); } public void managerAddSolder() throws Exception { connection=JdbcUtil.getConnection(); String name=bufIn.readLine(); System.out.println(name); preparedstatement=connection.prepareStatement("insert into solder(solder_name) values(?) "); preparedstatement.setString(1,name); preparedstatement.executeUpdate();//执行更新 preparedstatement=connection.prepareStatement("select *from solder where solder_number=(select MAX(solder_number)from solder) "); resultset=preparedstatement.executeQuery();//执行更新 if(resultset.next()) { bufOut.write("ok\n");//回馈查询信心 bufOut.flush(); String str=resultset.getString(1)+"#"+resultset.getString(2)+"#"+resultset.getString(3); bufOut.write(str+"\n");//回馈查询信心 bufOut.flush(); } else { bufOut.write("no\n");//回馈查询信心 bufOut.flush(); } JdbcUtil.release(resultset, preparedstatement, connection); } public void managerModifySolder() throws Exception { connection=JdbcUtil.getConnection(); String arr[] = null; String line=null; String number=bufIn.readLine(); preparedstatement=connection.prepareStatement("select *from solder WHERE solder_number=? "); preparedstatement.setString(1,number); resultset=preparedstatement.executeQuery(); if(resultset.next()) { bufOut.write("ok\n");//回馈查询信心 bufOut.flush(); line=bufIn.readLine(); arr=line.split("#"); preparedstatement=connection.prepareStatement("update solder set solder_password=?,solder_name=? WHERE solder_number=? "); preparedstatement.setString(1,arr[2]); preparedstatement.setString(2,arr[1]); preparedstatement.setString(3,arr[0]); preparedstatement.executeUpdate();//执行更新 } else { bufOut.write("no\n");//回馈查询信心 bufOut.flush(); } socket.close(); JdbcUtil.release(resultset, preparedstatement, connection); } public void managerDeleteSolder() throws Exception { connection=JdbcUtil.getConnection(); String number=bufIn.readLine(); preparedstatement=connection.prepareStatement("select *from solder WHERE solder_number=? "); preparedstatement.setString(1,number); resultset=preparedstatement.executeQuery(); if(resultset.next()) { bufOut.write("ok\n");//回馈查询信心 bufOut.flush(); preparedstatement=connection.prepareStatement("delete from solder WHERE solder_number=? "); preparedstatement.setString(1,number); preparedstatement.executeUpdate();//执行更新 } else { bufOut.write("no\n");//回馈查询信心 bufOut.flush(); } socket.close(); JdbcUtil.release(resultset, preparedstatement, connection); } }
以localhost/intsmaze/user/add?name=intsmaze的url来反向剖析tcp服务端如何接收,并调用对应方法。localhost是与服务器建立连接,然后发送intsmaze/user/add?name=intsmaze为一个数据到服务器,服务器接收到该字符串后,根据/截取,然后判断该请求是发给intsmaze的应用。然后通过user知道这个请求时user模块(用户管理模块),然后通过add知道是调用添加用户方法。?后面就是对于的参数获取存入数据库即可.
对上面的方法改进如下即可实现
String line=bufIn.readLine(); //读取第一个选着功能 line的值为intsmaze/user/add?name=intsmaze String arr[]=line.split("/"); String model=arr[1]; String method=arr[2].split("?")[0]; String param=arr[2].split("?")[1]; if(model.endsWith("user")) { if(method.equals("add")) { user.add(param); } } else if(model.equals("goods")) { ... } else if ...
作者:intsmaze(刘洋)
畅销书籍:《深入理解Flink核心设计与实践原理》作者
老铁,你的--->推荐,--->关注,--->评论--->是我继续写作的动力。
由于博主能力有限,文中可能存在描述不正确,欢迎指正、补充!
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。