Unity3D与JSP TomCat服务器传递数据和文件( 二 ) Unity3D向java传输表单

话不多说,我们先去Unity里创建一个可以输入用户名和密码的登录窗口

登录窗口

然后给登录按钮添加代码

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Login : MonoBehaviour
{
    //持有用户名和密码这两个输入框的对象
    public InputField Username;
    public InputField Password;

    //定义访问JSP登录表单的get方式访问路径
    private string Url = "http://192.168.31.38:8080/MyUnityToJSPTest/StringContentServlet.do?";

    //当按钮被点击
    public void LoginButtonOnClick()
    {
        //向服务器传递的参数
        string parameter = "";
        parameter += "UserName=" + Username.text + "&";
        parameter += "PassWord=" + Password.text;

        //开始传递
        StartCoroutine(login(Url + parameter));

    }

    //访问JSP服务器
    IEnumerator login(string path)
    {
        WWW www = new WWW(path);
        yield return www;
        //如果发生错误,打印这个错误
        if (www.error != null)
        {
            Debug.Log(www.error);
        }
        else
        {
            //如果服务器返回的是true
            if (www.text.Equals("true"))
            {
                //登陆成功
                print("Login Success!!!");
                Application.LoadLevel("UpLoadFile");
            }
            else
            {
                //否则登录失败
                print("Login Fail...");
            }
        }
    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

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

这里写图片描述

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

JSP接收表单

然后回到Unity,注册按钮点击事件。。。其实是我自己忘了——-

注册按钮点击事件

接着就是运行Unity。 
别忘了运行之前把JSP的服务器打开,否则提交不过去会报错的。

这里写图片描述

点击登录后,去JSP服务器看看控制台,是否已经把我们的用户名和密码输出出来了呢? 
我的代码省略的那部分大家可以进行什么注册啊,验证数据库什么的都可以,我个人感觉比Socket实用一些。

这里写图片描述

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

编辑模式下,给上传文件的按钮添加代码,注册点击事件

上传场景

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";

    //点击上传按钮
    public void OnUpFileButtonClick()
    {
        //设置上传文件中面板为显示状态
        upFileing.SetActive(true);
        //上传本地文件
        StartCoroutine(UpFileToJSP(Url, Application.dataPath + "\\midi.txt"));
    }



    //访问JSP服务器
    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();
            }
        }
    }  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84

创建三个面板

上传中
上传成功
上传失败

将三个面板拖拽给脚本后,打开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=='\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()=='\n'){
                    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();
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120

在写这个代码之前,我们要新建一个包 
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;
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

做完这些后,开启我们的服务器。然后开启Unity,在确保上传文件在Unity的Assets目录下的时候,我们就运行Unity,点击上传文件按钮。

可以看到Unity的控制台是这样的

上传成功

然后是JSP的控制台

JSP上传成功

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

browse

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

upload文件夹

好了。Unity向服务器上传文件已经成功,下面我们还差最后一步,也就是我在网上找不到的东西,用Unity请求服务器,服务器给Unity反馈一个文件,那么我们现在回到unity,编辑上传成功那个面板,当我们上传文件成功后弹出的那个面板下方会有播放的那个按钮。编辑这个按钮,添加点击事件,然后挂上脚本。 
代码如下:

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";

    //当按钮点击
    public void OnPlayButtonClick()
    {
        //向服务器传递指令
        StartCoroutine(UpFileToJSP(url));
    }

    //访问JSP服务器
    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");
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

在这个脚本之前,我们应该先到服务器的index.jsp添加一个表单,再去servlets包下注册一个Servlet供我们请求服务器所用。操作我就不详细介绍了,上一个文章里面有介绍,,一会我在下面附个链接。那么我直接上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!");
        }

    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

index.jsp

index.jsp

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

midi.mid

然后我们就部署一下工程 
开启服务器,正常启动后,打开Unity,开始运行。。。

点击那个小播放按钮后,我们可以去JSP的控制台查看

JSP下载成功

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

Unity下载文件成功

然后我们去Unity的工程目录下播放这个midi文件,看看是否能正常播放呢。

播放midi

反正我的是正常播放了。

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

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

QQ:531193915 
E_Mail:15210411296@163.com

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

补充一下。我把工程文件整理了一下。 
下面是地址: 
http://pan.baidu.com/s/1bTLkbs 
密码: 
aym5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值