Unity3D上路_05-网络相关
发布日期:2021-06-24 18:46:34 浏览次数:2 分类:技术文章

本文共 7777 字,大约阅读时间需要 25 分钟。

hot3.png

官网: 

4.5: 

一。基于HTTP的WWW组件

1.Get传输

1)脚本

WebManager.cs

using UnityEngine;using System.Collections;public class WebManager : MonoBehaviour {    string info = " ";    void OnGUI() {        GUI.Label(new Rect(100, 20, 300, 30), info);        if (GUI.Button(new Rect(100, 80, 200, 60), "Get访问")) {            StartCoroutine(IGetData());        }    }    IEnumerator IGetData() {        // 网络传输器(http://URL?参数=值&参数=值)        WWW www = new WWW("http://127.0.0.1:8080/HelloUnity/HelloUnity?Name=Eminem&Pasd=0999");        // yield 将需要return的数据全都放到迭代器内才执行        yield return www;        // www.text是请求响应后返回的数据        info = www.text.ToString();        // 如果发生url错误等意外        if (www.error != null) {            info = www.error.ToString();            yield return null;        }    }}

2)UI

GameObject,Create Empty,关联脚本,

3)启动服务器

(服务器创建方法见 一。4.)

4)访问

2.Post传输

1)脚本

升级WebManager.cs

using UnityEngine;using System.Collections;public class WebManager : MonoBehaviour {    string info = " ";    void OnGUI() {        GUI.Label(new Rect(100, 20, 300, 30), info);        if (GUI.Button(new Rect(100, 80, 200, 60), "Get访问")) { StartCoroutine(IGetData()); }        if (GUI.Button(new Rect(100, 180, 200, 60), "Post访问")) {            StartCoroutine(IPostData());        }     }    IEnumerator IGetData() { 略 }    IEnumerator IPostData() {        Hashtable headers = new Hashtable();    // 键值对存储        headers.Add("Contend-Type", "application/x-www-form-urlencoded");   // 1.http头        string data = "Name=Alizee&Pasd=3745";  // 参数        byte[] bs = System.Text.UTF8Encoding.UTF8.GetBytes(data);   // 1.数据。将参数转为字节        // 3.网络传输器(URL,数据,http头)        WWW www = new WWW("http://127.0.0.1:8080/HelloUnity/HelloUnity", bs, headers);        // yield 将需要return的数据全都放到迭代器内才执行        yield return www;        info = www.text.ToString();        // 如果发生url错误等意外        if (www.error != null) {            info = www.error.ToString();            yield return null;        }    } }

2)访问

3)WWWForm提交数据

using UnityEngine;using System.Collections;public class WebManager : MonoBehaviour {    void OnGUI() {        if (GUI.Button(new Rect(100, 130, 200, 30), "WWWForm访问")) {            StartCoroutine(WwwFormPost());        }    }    IEnumerator WwwFormPost() {        //网页表单,辅助类。用来生成表单数据,使用WWW类传递到web服务器        WWWForm form = new WWWForm();        // AddField(参数名,值)        form.AddField("caonima", "dsdssds");        form.AddField("rininai", "365djyut");        // post方法( URL,表单 )        WWW www = new WWW("http://127.0.0.1:8080/HelloUnity/UnityImage", form);        yield return www;        if (www.error != null) {            info = www.error.ToString();            yield return null;        }    }}

3.图片上传下载

 

1)脚本

升级WebManager.cs

using UnityEngine;using System.Collections;public class WebManager : MonoBehaviour {    string info = " ";    public Texture2D m_uploadImage;         // 上传的图片    private Texture2D m_downloadTexture;     // 下载的图片    void OnGUI() {        GUI.Label(new Rect(100, 10, 300, 50), info);        if (GUI.Button(new Rect(100, 70, 200, 30), "Get访问")) { StartCoroutine(IGetData()); }        if (GUI.Button(new Rect(100, 120, 200, 30), "Post访问")) { StartCoroutine(IPostData()); }        if (GUI.Button(new Rect(100, 170, 200, 30), "请求图片")) {            StartCoroutine(IRequestPNG());        }         // 如果服务器返回了图片信息,绘制        if (m_downloadTexture != null) {            GUI.DrawTexture(new Rect(100, 220, 256, 256), m_downloadTexture);        }     }    IEnumerator IGetData() { 略 }    IEnumerator IPostData() { 略 }    IEnumerator IRequestPNG() {         m_downloadTexture = new Texture2D(256, 256);    // 须初始化            // 图片转字节        byte[] bs = m_uploadImage.EncodeToPNG();          //网页表单,辅助类。用来生成表单数据,使用WWW类传递到web服务器        WWWForm form = new WWWForm();         // 添加二进制数据到表单(参数名,值-源数据,目标文件名,文件类型)        /**         * 提交文件,只能是post方式         * WWWForm同html中声明属性enctype="multipart/form-data"         * 对应http协议请求:          *  Content-Type: image/png         *  Content-disposition: form-data; name="unityPic"; filename="picUnity"    */        form.AddBinaryData("unityPic", bs, "picUnity", "image/png");                // post方法( URL,表单 )        WWW www = new WWW("http://127.0.0.1:8080/HelloUnity/UnityImage", form);        yield return www;        info = "图片:" + www.text; // 服务器返回的图片地址保存在这里面         /**************************************************/        // 下载网络图片        WWW www2 = new WWW(www.text);        //等待直到下载完全结束        yield return www2;        // 指定下载的图像到物体的主纹理        // 必须是JPG或者PNG格式格式的图片        www2.LoadImageIntoTexture(m_downloadTexture);    } }

2)访问

4.补充:Java服务器架设

Tomcat+MyEclipse。

1)纯文本交互Servlet

package cuiweiyou;import *;public class HelloUnity extends HttpServlet {		/** 响应 get 请求 **/	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {		req.setCharacterEncoding("UTF-8");		resp.setContentType("text/html; charset=UTF-8");				// 获取Unity通过get发送来的参数		String name = req.getParameter("Name");		String pasd = req.getParameter("Pasd");				System.out.println("收到Unity通过get发来的数据,Name:" + name + ", Pasd:" + pasd);				// 向Unity发送消息		resp.getWriter().write("GET到 你的用户名:" + name + ",密码:" + pasd);	}	/** 响应  post 请求 **/	protected void doPost(HttpServletRequest req, HttpServletResponse resp)			throws ServletException, IOException {		req.setCharacterEncoding("UTF-8");		resp.setContentType("text/html; charset=UTF-8");				// 获取Unity通过get发送来的参数		String name = req.getParameter("Name");		String pasd = req.getParameter("Pasd");				System.out.println("收到Unity通过post发来的数据,Name:" + name + ", Pasd:" + pasd);				// 向Unity发送文本消息		resp.getWriter().write("Post到 你的用户名:" + name + ",密码:" + pasd);	}}

2)图片上传下载Servlet

package cuiweiyou;import * ; // 用到了 commons-fileupload-*.jar,http://commons.apache.org/proper/commons-fileupload/ public class UnityImage extends HttpServlet {	/** 响应 form的post 请求 **/	protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {		request.setCharacterEncoding("UTF-8");		resp.setContentType("text/html; charset=UTF-8");		// true:request支持文件上传;false:request出了问题,如
没有添加ENCTYPE="multipart/form-data" if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); // 磁盘 ServletFileUpload upload = new ServletFileUpload(factory); // 文件 try { // 解析request对象,得到一个保存全部上传数据的List对象 List
files = upload.parseRequest(request); for (FileItem file : files) { // 取出上传文件的文件名称 String name = file.getName(); // Unity的WWWForm上传来的不带后缀名 // 获取文件类型 String type =   "." + file.getContentType().substring( file.getContentType().indexOf("/") + 1 ); // 保存在服务器的目标目录 String path =   this.getServletContext().getRealPath("/") + File.separatorChar + name + type; // 如果不是纯文本数据,即是文件 if (!file.isFormField() && type.equals(".png")) { // 上传文件 File uploadedFile = new File(path); file.write(uploadedFile); // 向Unity发送消息(服务器名+端口+项目名+文件) resp.getWriter().write("http://" +   request.getServerName() + ":" + request.getServerPort() +   request.getContextPath() + "/" + name + type); } else{ // 向Unity发送消息 resp.getWriter().write("限定使用png格式图片!"); } } } catch (Exception e) { e.printStackTrace(); } } }}

3)web.xml

HelloUnity
cuiweiyou.HelloUnity
HelloUnity
/HelloUnity
UnityImage
cuiweiyou.UnityImage
UnityImage
/UnityImage

二。基于UDP的Network组件

脑力有限,请大牛指点!

三。基于C#-Socket

脑力有限,请大牛指点!

- end

转载于:https://my.oschina.net/vigiles/blog/282814

转载地址:https://blog.csdn.net/weixin_34248258/article/details/91919861 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LruCache的理解
下一篇:Mysql自定义主键查询排序

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年04月08日 05时56分49秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章