unity与服务器通信 给后端发送消息

您所在的位置:网站首页 男生真人头像可爱图片动漫 unity与服务器通信 给后端发送消息

unity与服务器通信 给后端发送消息

2024-03-19 04:41| 来源: 网络整理| 查看: 265

之前提到的船舶项目,导师要求从unity里发送消息给前端(已经在之前的博客里分享了实现方法,但是当时还没实现),然后初步的想法是后端可以发送消息给前端,那么unity是否可以发送消息给后端?一直都是后端接口发送消息,unity从后端接口获取数据,第一次思考反方向发送的可能性。经过各种尝试后,成功实现了。unity中已经提供了UnityWebRequest 类用来实现消息的收发,记得导入using UnityEngine.Networking;。要发送的消息裹挟在后端接口中,代码如下:

//定义访问JSP登录表单的get方式访问路径 private string Url = "http://localhost:8080/Shop/login?userName=1&passWord=2"; public void senddingData() { Debug.Log("sendding"); StartCoroutine(login(Url)); } //访问JSP服务器 IEnumerator login(string path) { UnityWebRequest www = new UnityWebRequest(path);//创建UnityWebRequest对象 yield return www.SendWebRequest(); //等待返回请求的信息 if (www.isHttpError || www.isNetworkError) //如果其 请求失败,或是 网络错误 { Debug.Log(www.error); //打印错误原因 } else //请求成功 { Debug.Log("Get:请求成功"); } }

用来测试的对接的后端是简单创建的jsp+servlet系统,servlet层的接收代码如下,成功在控制台收到了1+2。

@WebServlet("/login") public class Login extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("userName"); String passWord = request.getParameter("passWord"); System.out.println(userName+":"+passWord); //Writer out = response.getWriter(); if(userName!=null||passWord!=null) { System.out.println("获取成功"); }else { System.out.println("获取失败"); } } }


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3