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的代碼我就不復制過來了,自己打一遍。印象深刻,最好是看懂了背著打。這樣才有意義。
然後回到Unity。註冊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==‘\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();
}
}
}
在寫這個代碼之前,我們要新建一個包
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的控制臺
這些都證明不了什麽,我們要看到文件才證明我們上傳成功
點擊部署文件的那個button。以下有一個Browse
點開之後會看到我們server上的文件夾
那麽就能夠看到我們用代碼生成的upload的文件夾可裏面的midi.txt文件了
好了。
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
unity要下載server上的文件,那我們要給server上放一個我們準備上傳的文件,就是這個midi.mid,這是個音頻。
然後我們就部署一下project
開啟server,正常啟動後。打開Unity,開始執行。。。
點擊那個小播放button後,我們能夠去JSP的控制臺查看
然後是Unity的控制臺,等控制臺出現成功以後,等一小會Unity引擎就會把文件解析並顯示出來。
然後我們去Unity的project文件夾下播放這個midi文件,看看能否正常播放呢。
反正我的是正常播放了。
好了,關於Unity與JSP的通信我就分享到這裏吧。再說一次我不是什麽大神,僅僅是喜歡研究與學習,如有不足之處,歡迎指正,謝謝。
聯系方式
查看Aries的個人資料
QQ:531193915
E_Mail:[email protected]
轉載請註明出處。謝謝 。
本文永久鏈接:http://blog.csdn.net/aries_h/article/details/50971981
補充一下。我把project文件整理了一下。
以下是地址:
http://pan.baidu.com/s/1bTLkbs
password:
aym5
Unity3D與JSP TomCatserver傳遞數據和文件( 二 ) Unity3D向java傳輸表單