• Unity3D与JSP TomCatserver传递数据和文件( 二 ) Unity3D向java传输表单



    扫码关注微信公众号,获取最新资源

    订阅号二维码


    经历了一天的工作。我又来更新啦。。。白天手欠,把上一个给删了。明天重写吧。。

    废话不多说。我们先去Unity里创建一个能够输入username和password的登录窗体

    登录窗体

    然后给登录button加入代码

    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class Login : MonoBehaviour
    {
        //持实username和password这两个输入框的对象
        public InputField Username;
        public InputField Password;
    
        //定义訪问JSP登录表单的get方式訪问路径
        private string Url = "http://192.168.31.38:8080/MyUnityToJSPTest/StringContentServlet.do?

    "; //当button被点击 public void LoginButtonOnClick() { //向server传递的參数 string parameter = ""; parameter += "UserName=" + Username.text + "&"; parameter += "PassWord=" + Password.text; //開始传递 StartCoroutine(login(Url + parameter)); } //訪问JSPserver IEnumerator login(string path) { WWW www = new WWW(path); yield return www; //假设错误发生。打印这个错误 if (www.error != null) { Debug.Log(www.error); } else { //假设server返回的是true if (www.text.Equals("true")) { //登陆成功 print("Login Success!!!"); Application.LoadLevel("UpLoadFile"); } else { //否则登录失败 print("Login Fail..."); } } } }

    将两个面板拖拽给脚本生成实例

    这里写图片描写叙述

    然后我们去JSPserver接收Unity传过来的值
    JSP的代码我就不复制过来了,自己打一遍。印象深刻,最好是看懂了背着打。这样才有意义。

    JSP接收表单

    然后回到Unity。注冊button点击事件。

    。。事实上是我自己忘了——-

    注冊button点击事件

    接着就是执行Unity。


    别忘了执行之前把JSP的server打开。否则提交只是去会报错的。

    这里写图片描写叙述

    点击登录后。去JSPserver看看控制台。是否已经把我们的username和password输出出来了呢?
    我的代码省略的那部分大家能够进行什么注冊啊,验证数据库什么的都能够,我个人感觉比Socket实用一些。

    这里写图片描写叙述

    好了,注冊和登录什么的都是传递字符串,这个我们已经做完了,事实上并没有什么难点,那么我们继续回到Unity,開始上传文件的分享。
    刚才点击登录button后。是否成功进入了上传文件的场景呢?
    以下我们来编辑一下上传的场景

    编辑模式下,给上传文件的button加入代码。注冊点击事件

    上传场景

    using System;
    using System.IO;
    using UnityEngine;
    using System.Collections;
    
    public class UpFile : MonoBehaviour
    {
        //持有三个状态面板的对象
        public GameObject upFileing;
        public GameObject successPanel;
        public GameObject failPanel;
    
        //定义訪问JSP登录表单的post方式訪问路径
        private string Url = "http://192.168.31.39:8080/MyUnityToJSPTest/ByteFileContentServlet.do";
    
        //点击上传button
        public void OnUpFileButtonClick()
        {
            //设置上传文件里面板为显示状态
            upFileing.SetActive(true);
            //上传本地文件
            StartCoroutine(UpFileToJSP(Url, Application.dataPath + "\midi.txt"));
        }
    
    
    
        //訪问JSPserver
        private IEnumerator UpFileToJSP(string url, string filePath)
        {
            WWWForm form=new WWWForm();
            form.AddBinaryData("midiFile",FileContent(filePath),"midi.txt");
    
            WWW upLoad=new WWW(url,form);
            yield return upLoad;
            //假设失败
            if (!string.IsNullOrEmpty(upLoad.error)||upLoad.text.Equals("false"))
            {
                //在控制台输出错误信息
                print(upLoad.error);
                //将失败面板显示  上传中不显示
                upFileing.SetActive(false);
                failPanel.SetActive(true);
            }
            else
            {
                //假设成功
                print("Finished Uploading Screenshot");
                //将成功面板显示  上传中不显示
                upFileing.SetActive(false);
                successPanel.SetActive(true);
            }
    
        }
    
    
    
        //将文件转换为字节流
        private byte[] FileContent(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            try
            {
                byte[] buffur = new byte[fs.Length];
                fs.Read(buffur, 0, (int)fs.Length);
    
                return buffur;
            }
            catch (Exception ex)
            {
                Debug.Log(ex.Message);
                return null;
            }
            finally
            {
                if (fs != null)
                {
    
                    //关闭资源  
                    fs.Close();
                }
            }
        }  
    }
    

    创建三个面板

    上传中
    上传成功
    上传失败

    将三个面板拖拽给脚本后,打开JSP中的ByteFileContentServlet.java

    编写代码

    package com.Aries.Servlets;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.io.RandomAccessFile;
    import java.io.Writer;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.Aries.Tools.Tool;
    
    public class ByteFileContentServlet extends HttpServlet {
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
        {
            //向控制台输出文件的内容长度
            System.out.println(request.getContentLength());
            //假设有内容
            if (request.getContentLength() > 297) {
    
    
                //==================開始处理文件===================
    
                //接收上传文件内容中暂时文件的文件名称
                String tempFileName = new String("tempFileName.txt");
                //tempfile 对象指向暂时文件
                File tempFile = new File(request.getRealPath("/")+tempFileName);
                //outputfile 文件输出流指向这个暂时文件
                FileOutputStream outputStream = new FileOutputStream(tempFile);
                //得到客服端提交的全部数据
                InputStream fileSourcel = request.getInputStream();
                //将得到的客服端数据写入暂时文件
                byte b[] = new byte[1000];
                int n ;
                while ((n=fileSourcel.read(b))!=-1){
                    outputStream.write(b,0,n);
                }
    
                //关闭输出流和输入流
                outputStream.close();
                fileSourcel.close();
    
                //randomFile对象指向暂时文件
                RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
                //读取暂时文件的前三行数据
                randomFile.readLine();
                randomFile.readLine();
                randomFile.readLine();
                //读取暂时文件的第四行数据,这行数据中包括了文件的路径和文件名称
                String filePath = randomFile.readLine();
                //得到文件名称
                System.out.println(filePath);
                int position = filePath.lastIndexOf("filename");
                String filename =Tool.codeString(filePath.substring(position+10,filePath.length()-1));
                //又一次定位读取文件指针到文件头
                randomFile.seek(0);
                //得到第四行回车符的位置,这是上传文件数据的開始位置
                long  forthEnterPosition = 0;
                int forth = 1;
                while((n=randomFile.readByte())!=-1&&(forth<=4)){
                    if(n=='
    '){
                        forthEnterPosition = randomFile.getFilePointer();
                        forth++;
                    }
                }
    
                //生成上传文件的文件夹
                File fileupLoad = new File(request.getRealPath("/"),"upLoad");
                fileupLoad.mkdir();
                //saveFile 对象指向要保存的文件
                File saveFile = new File(request.getRealPath("/")+"\upLoad",filename);
                RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
                //找到上传文件数据的结束位置。即倒数第四行
                randomFile.seek(randomFile.length());
                long endPosition = randomFile.getFilePointer();
                int j = 1;
                while((endPosition>=0)&&(j<=4)){
                    endPosition--;
                    randomFile.seek(endPosition);
                    if(randomFile.readByte()=='
    '){
                        j++;
                    }
                }
    
                //从上传文件数据的開始位置到结束位置。把数据写入到要保存的文件里
                randomFile.seek(forthEnterPosition);
                long startPoint = randomFile.getFilePointer();
                while(startPoint<endPosition){
                    randomAccessFile.write(randomFile.readByte());
                    startPoint = randomFile.getFilePointer();
                }
                //关闭文件输入、输出
                randomAccessFile.close();
                randomFile.close();
                tempFile.delete();
    
                //==================处理文件结束===================
    
                //向控制台输出文件上传成功
                System.out.println("File upload success!");
            } 
            else 
            {
                //否则显示失败,
                System.out.println("No file!");
    
                //向Unity返回一个Fasle字符串
                Writer out=response.getWriter();
                out.write("false");
                out.close();
            }
        }
    
    }

    在写这个代码之前,我们要新建一个包
    com.Aries.Tools
    在里面新建一个工具类Tool.java

    代码例如以下

    注:这里包括以下要用到的处理工具,我就一起附上来了

    package com.Aries.Tools;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.UnsupportedEncodingException;
    
    public class Tool {
    
        /** 文件字节流 */
        public static byte[] getBytes(String filePath) {
            byte[] buffer = null;
            try {
                File file = new File(filePath);
                FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
                byte[] b = new byte[1000];
                int n;
                while ((n = fis.read(b)) != -1) {
                    bos.write(b, 0, n);
                }
                fis.close();
                bos.close();
                buffer = bos.toByteArray();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return buffer;
        }
    
        /** 处理中文字符串的函数 */
        public static String codeString(String str) {
            String s = str;
            try {
                byte[] temp = s.getBytes("UTF-8");
                s = new String(temp);
                return s;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return s;
            }
        }
    
    }

    做完这些后。开启我们的server。然后开启Unity,在确保上传文件在Unity的Assets文件夹下的时候。我们就执行Unity。点击上传文件button。

    能够看到Unity的控制台是这种

    上传成功

    然后是JSP的控制台

    JSP上传成功

    这些都证明不了什么,我们要看到文件才证明我们上传成功
    点击部署文件的那个button。以下有一个Browse

    browse

    点开之后会看到我们server上的文件夹
    那么就能够看到我们用代码生成的upload的文件夹可里面的midi.txt文件了

    upload文件夹

    好了。

    Unity向server上传文件已经成功,以下我们还差最后一步,也就是我在网上找不到的东西,用Unity请求server,server给Unity反馈一个文件,那么我们如今回到unity。编辑上传成功那个面板。当我们上传文件成功后弹出的那个面板下方会有播放的那个button。编辑这个button,加入点击事件。然后挂上脚本。


    代码例如以下:

    using System.IO;
    using System.Xml.Serialization;
    using UnityEngine;
    using System.Collections;
    
    public class DownLoadFile : MonoBehaviour
    {
        //定义訪问JSP登录表单的get方式訪问路径
        private string url = "http://192.168.31.39:8080/MyUnityToJSPTest/DownloadMidi.do?Download=Midi";
    
        //当button点击
        public void OnPlayButtonClick()
        {
            //向server传递指令
            StartCoroutine(UpFileToJSP(url));
        }
    
        //訪问JSPserver
        private IEnumerator UpFileToJSP(string url)
        {
            WWW downLoad = new WWW(url);
            yield return downLoad;
            //假设失败
            if (!string.IsNullOrEmpty(downLoad.error) || downLoad.text.Equals("false"))
            {
                //在控制台输出错误信息
                print(downLoad.error);
            }
            else
            {
                //假设成功
                //定义一个字节数组保存文件
                byte[] myByte = downLoad.bytes;
                //新建一个文件接收字节流
                FileStream fs = new FileStream(Application.dataPath + "/midi.mid",FileMode.Create, FileAccess.Write, FileShare.None);
                //開始转换
                fs.Write(myByte,0,myByte.Length);
                //刷新流
                fs.Flush();
                //关闭流
                fs.Close();
                //子啊控制台输出完毕信息
                print("Finished Uploading Screenshot");
            }
        }
    }
    

    在这个脚本之前,我们应该先到server的index.jsp加入一个表单。再去servlets包下注冊一个Servlet供我们请求server所用。操作我就不具体介绍了。上一个文章里面有介绍,,一会我在以下附个链接。那么我直接上JSP上这个Servlet的代码和index.jsp的表单怎样加入。

    Servlet:DownloadMidi.java

    package com.Aries.Servlets;
    
    import java.io.IOException;
    
    import java.io.OutputStream;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.Aries.Tools.Tool;
    
    public class DownloadMidi extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    
            //假设訪问參数符合条件
            if(request.getParameter("Download").equals("Midi"))
            {
                //获取输出流
                OutputStream out=response.getOutputStream();
                //把文件变成byte字节流传入输出流
                out.write(Tool.getBytes(request.getRealPath("/")+"\upLoad\midi.mid"));
                //刷新流
                out.flush();
                //关闭流
                out.close();
                //向控制台提示成功
                System.out.println("success!");
            }
    
        }
    
    
    }
    

    index.jsp

    index.jsp

    unity要下载server上的文件,那我们要给server上放一个我们准备上传的文件,就是这个midi.mid,这是个音频。

    midi.mid

    然后我们就部署一下project
    开启server,正常启动后。打开Unity,開始执行。。。

    点击那个小播放button后,我们能够去JSP的控制台查看

    JSP下载成功

    然后是Unity的控制台,等控制台出现成功以后,等一小会Unity引擎就会把文件解析并显示出来。

    Unity下载文件成功

    然后我们去Unity的project文件夹下播放这个midi文件,看看能否正常播放呢。

    播放midi

    反正我的是正常播放了。

    好了,关于Unity与JSP的通信我就分享到这里吧。再说一次我不是什么大神,仅仅是喜欢研究与学习,如有不足之处,欢迎指正,谢谢。

    联系方式
    查看Aries的领英个人资料 查看Aries的个人资料

    QQ:531193915
    E_Mail:15210411296@163.com

    转载请注明出处。谢谢 。
    本文永久链接:http://blog.csdn.net/aries_h/article/details/50971981

    补充一下。我把project文件整理了一下。
    以下是地址:
    http://pan.baidu.com/s/1bTLkbs
    password:
    aym5

  • 相关阅读:
    浮动float 摆放位置
    边框(border)宽度样式颜色 和基本属性
    调用css文件,进行调色
    deque_01
    iterator_教程中的讲解
    vector_01
    VS2013_CodeLens
    Qt for Embedded Linux
    jsjl_for_ubuntu12.04
    VC6_导入lib库
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/7107301.html
Copyright © 2020-2023  润新知