پاسخ داده شده: اتصال به سرور nodejs بوسیله یونیتی
برای استفاده از کلاس زیر باید کتابخانه SimpleJson به پروژه یونیتی اضافه کنید .
و از اونجایی که مهم هست Start کلاس ServerRequest قبل از بقیه کلاس ها اجرا بشه ترتیب اجرای این اسکریپت رو داخل ادیتور یونیتی و از طریق
Edit/Project setting/Script execution order تغییر بدید.
ماژول های express و همینطور body-parser روهم بوسیله npm در nodejs نصب کنید .
سمت یونیتی :
using SimpleJSON;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using UnityEngine;
using UnityEngine.Networking;
public class ServerRequest : MonoBehaviour
{ public delegate void RequestCallBack(SimpleJSON.JSONNode node); public static string server = "http://localhost:1212/api/"; public static string test= server + "test"; private static ServerRequest serverRequest; private void Start() { serverRequest = this; } public static void SendRequest(String url, RequestCallBack requestCallBack, params KeyValuePair<string, string>[] vals) { serverRequest.StartCoroutine(serverRequest.request(url, requestCallBack, vals)); } private IEnumerator request(String url, RequestCallBack requestCallBack, params KeyValuePair<string, string>[] vals) { JSONNode cl = new SimpleJSON.JSONObject(); for(int i = 0; i < vals.Length; i++) { cl[vals[i].Key] = vals[i].Value; } using(UnityWebRequest www = new UnityWebRequest(url, "POST")) { byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(cl.ToString()); www.uploadHandler = new UploadHandlerRaw(bodyRaw); www.downloadHandler = new DownloadHandlerBuffer(); www.SetRequestHeader("Content-Type", "application/json"); yield retu www.SendWebRequest(); if(www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { string response = www.downloadHandler.text; if(response != null) { JSONNode json = JSON.Parse(response); requestCallBack(json); } } } }
}
نحوه استفاده از این کلاس :
ServerRequest.SendRequest(ServerRequest.login, (jsonNode) => { Debug.Log("Response of server : " + jsonNode.ToString()); //more code }, new KeyValuePair<string, string>("test_param", "test value"));
کد nodejs :
'use strict';
let express = require('express');
let bodyParser = require('body-parser');
let app = express();
let router = express.Router();
let port = 1212;
app.use(bodyParser.json());
function getdata(jsondata) { var stringify = JSON.stringify(jsondata); var json = JSON.parse(stringify); retu json;
}
router.use(function (req, res, next) { res.set('Content-Encoding', 'application/json'); // console.log(req); next();
});
router.route('/test') .post(function (req, res) { var data = getdata(req.body); var test_param = data['test_param']; console.log("Data recieved in nodejs : "+test_param); //send back some data res.json({ 'result': 'every thing is ok !'});
});
app.use('/api', router);
console.log('server started on port ' + port);
app.listen(port);
