转一篇Unity客户端与Java服务器的通信

转自:http://www.programering.com/a/MTNxYDMwATQ.html

A few days ago a friend asked me about Unity3D inside Protobuf, was something to write this off until now, feel shy.

In this paper, the test environment:

System: WINDOWS 7 (third, 6), OS (fourth) X 10.9

Software: VS 2012 (third, 6), Eclipse (fifth, 6)

Hardware: iPad 2 (fourth), Macbook Pro Mid 2012 (step fourth)

Article directory:

1, About Protobuf C#

2, Why some Protobuf released to the iOS is not, even some in the PC are used?

3, Protobuf C# version of the manual processing

3.1, Create a C# project, the first manual create each through the Protobuf serialization or deserialization of data model classes, and then export the DLL

3.2, Create a serialized C# project, and then run the generated DLL

3.3, The above two projects generated DLL onto unity

4, In Unity deserialization Protobuf

5, The server Java with Protobuf

6, Too much bother?! The client will automatically handle Protobuf

1, About Protobuf C#

First of all, U3D Protobuf is using C# to achieve, so there are several optional C# implementation:

C#: http://code.google.com/p/protobuf-csharp-port
C#: http://code.google.com/p/protosharp/
C#: 
C#/.NET/WCF/VB: http://code.google.com/p/protobuf-net/

Here I used is the http://code.google.com/p/protobuf-net/ (you can download his code and tools in https://code.google.com/p/protobuf-net/downloads/list here), It is a relatively good, Provide a variety of platform support, After decompression in the "Full" directory can be seen in every platform support

See the inside of the unity, it will be ready to use our protobuf-net.dll.

2, Why some Protobuf released to the iOS is not, even some in the PC are used?

a, Protobuf uses JIT, namely in the run-time dynamic compilation, and the characteristics in the Unity release to the iOS is not supported. Therefore, cause you can run on PC, released to the iOS have a problem.

b, Protobuf is based on the.Net 2 framework, while Unity only supports.Net 2, or some characteristics more 2, and you release set a subset of.Net 2 in Unity. You only need to modify the latter can be set up in Player setting.

The above two can also be applied to other third party libraries, if you download a PC or C# inside the normal use of the library, in which U3D can not be used, so please check whether it is the result of the above two reasons.

3, Protobuf C# version of the manual processing

Know the above problems, as long as we choose a.Net2.0 Protobuf, then it is not a JIT, it can be used as normal.

Here is the idea of:

3.1, Create a C# project, the first manual create each through the Protobuf serialization or deserialization of data model classes, and then export the DLL

In the case of VS, first, create a class library project: "file" > " > " new " " > " " (remember to choose.Net framework 2)

The unity protobuf DLL add to project references

Then assume that you have a class WorkerInfo is needed by Protobuf serialization and deserialization, then create a WorkerInfo class, as follows:

using System;
using System.Collections.Generic;
using System.Text;
using ProtoBuf;
namespace Com.YourCompany.Project.Proto.Module{
    [ProtoContract]
    public class WorkerInfo { 

        [ProtoMember(1)]
        public int workerId;

        [ProtoMember(2)]
        public int leftClosingTimeSec;

        [ProtoMember(3)]
        public int buildingId;

    }
}

Press Shift+ F6 DLL, the project‘s bin\Debug directory can be found ProtoModelDLL.dll.

3.2, Create a serialized C# project, and then run the generated DLL
Also in the case of VS, first create a console application: "file" > " > " new " " > " " console application; (remember to choose.Net framework 2)

Add the Protobuf and the 3.1 generation DLL to reference

Written in the project generated in Program.cs:

using System;
using System.Collections.Generic;
using System.Text;
using ProtoBuf.Meta;
using ProtoBuf;
using ProtoBuf.Compiler;
using Com.YourCompany.Project.Proto.Module;

namespace ProtoModelSerializerCreator
{
    class Program
    {
        static void Main(string[] args)
        {
            var model = TypeModel.Create();

            model.Add(typeof(object), true);
            model.Add(typeof(WorkerInfo), true);

            model.AllowParseableTypes = true;
            model.AutoAddMissingTypes = true;
            model.Compile("ProtoModelSerializer", "ProtoModelSerializer.dll");
        }
    }
}

Then ctrl+ F5 operation, you can see the ProtoModelSerializer.dll in bin\Debug.

3.3, The above two projects generated DLL (ProtoModelDLL.dll and ProtoModelSerializer.dll) and protobuf-net.dll onto unity

How to use the fourth step?

4, In Unity deserialization Protobuf

Because of the general game client requests data volume is simple, less, therefore we request is not directly in front of the binary request. The front end is received and returned by Protobuf, and so. This discussion Protobuf deserialization.

The following code is very simple, write a test code:

using UnityEngine;
using System.Collections;
using ProtoBuf.Meta;
using Com.YourCompany.Project.Proto.Module;
using System.IO;
using Com.Duoyu001.Proto.Building;
using Com.Duoyu001.Proto.Worker;

public class TestProto : MonoBehaviour
{

	// init
	void Start ()
	{
		byte[] dataFromServ = new byte[]{8, 233, 7, 16, 100, 24, 1};	//these bytes are generated by server

		RuntimeTypeModel serializer = BitchSerializer.Create ();
		System.IO.MemoryStream memStream = new System.IO.MemoryStream ();
		WorkerInfo w = new WorkerInfo ();
		serializer.Deserialize (memStream, w, w.GetType ());	//asign value to proto model

		Debug.Log (w.workerId + ", " + w.buildingId + ", " + w.leftClosingTimeSec);
	}
}

After running the Unity console output worker information. The dataFromServ byte array code in the content of the actual communication when the rear end should be returned. This test is not related to Socket communication of knowledge.

5, The server Java with Protobuf

To see a client using Protobuf so much trouble, how will it end? In fact, the back-end is relatively simple, with the official Google support.

Download: https://code.google.com/p/protobuf/downloads/list

After decompression is such(2.5.0):

Into the "protobuf-2.5.0\java" folder, There is a maven project, You create a protobuf-java-2.5.0.jar in the target directory will use the Maven clean install jar package., No Maven download here., I used to generate maven. This time to import your Java project. You can.

And then you write a proto file, called "protobuf-2.5.0\src" inside the protoc.exe is generated, it will help you to generate a java file. (see https://developers.google.com/protocol-buffers/docs/javatutorial), here I have to provide a bat, used to call the protoc to generate the java file, manual input words too much trouble. Save it to.Bat and then double-click can be run under Windows.

@echo off
echo ** setting runtime variable

REM _protoSrc is your proto file directory location
set _protoSrc=F:\project_proto_src\trunk\xgame-controllers\protos

REM protoExe is used for the proto generated from the Java protoc.exe program position
set protoExe=C:\Users\john\Desktop\protobuf-2.5.0\src\protoc.exe

REM java_out_file to store the generated Java file directory location
set java_out_file=F:\project_proto_src\trunk\xgame-controllers\src\main\java
for /R "%_protoSrc%" %%i in (*) do (
	set filename=%%~nxi
	if "%%~xi"  == ".proto" (
		%protoExe% --proto_path=%_protoSrc% --java_out=%java_out_file% %%i
	)
)

OK, you just put the generated Java copied to or directly into a Java project your source directory, then you can use the. For example: 
As said before WorkerInfo as an example

package com.duoyu001.xgame;

import java.util.Arrays;

import com.duoyu001.xgame.worker.proto.WorkerInfoBuilder.WorkerInfo;

public class TestProto {

	public static void main(String[] args) {
		WorkerInfo w = WorkerInfo.newBuilder().setBuildingId(1)
				.setLeftClosingTimeSec(100).setWorkerId(1001).build();
		byte[] byteArray = w.toByteArray();
		System.out.println(Arrays.toString(byteArray));
	}
}

The console will output: 

The careful students will find the byte and above the "8, 233, 7, 16, 100, 24, 1" is not quite the same. Second numbers are -23 and 233

In fact, this is only byte has no symbolic difference.

Their binary representation is: 11101001

6, Too much bother?! The client will automatically handle Protobuf

We see the client is not a class, will need to increase the code in two project in VS, and the rear end is directly based on the proto generated code file. So, it seems a bit unfair, and that before and after the end of may produce different. In fact, protobuf I personally feel that the biggest benefit:

a, A small amount of data

b, The proto generated code template, reduce the front end alignment

But now only reduces the working front end, did not decrease, so the second advantage is not obvious.

That would be fine. I‘m not so satisfied. Therefore, I decided, front end to generate the CS file based on proto.

Therefore, I use Java to compile a Proto file analysis tools, and according to the proto to generate the CS file, and then used to construct the executive vs program bat invokes the vs command line, the last generation of two DLL.

I put the above command are integrated into a bat, so the bat task is:

The execution of a java program, proto files to generate CS files.

The use of vs interface to construct two vs projects, generating two DLL.

Through the SVN to the two DLL submitted to the client on the trunk.

Call it according to the proto Java generated bat fragments, java code generation.

Through the SVN to generate java code is submitted to the server on the trunk.

Therefore, in this way, now as long as the compiled proto file, and then double-click the bat, before and after the end of available Protobuf data object through the latest update SVN.

Bat operation

According to the proto CS file is generated and compiled two vs projects, then the generated DLL submitted to SVN

Java code is generated and submitted to SVN

This step operation we are interested can try, there are problems discussed in this blog welcome.

时间: 2024-08-14 23:08:17

转一篇Unity客户端与Java服务器的通信的相关文章

解如何利用 XML 和 JavaScript Object Notation 在 Ajax 客户端和 Java 服务器之间传输数据。

2006 年 6 月发表 Ajax 核心 API(即所谓的 XMLHttpRequest)的唯一用途就是发送 HTTP 请求,在 Web 浏览器与服务器之间进行数据交换.Web 页面中运行的 JavaScript 代码,可以使用 XMLHttpRequest 将该请求参数提交至服务器端脚本,例如 Servlet 或 JSP 页面.调用的 Servlet/JSP 将发回一个响应,其中包含了一般用于不需刷新整个页面即可更新用户查看内容的数据.此种方法在性能和可用性方面均体现出了独有的优势,因为这将降

Android客户端与本地服务器Socket通信

Android客户端与本地服务器Socket通信 Socket服务器运行结果图?? 一.客户端和服务器端的选择: 客户端是我们手机端,关于服务器端,只要安装了JDK,自然就拥有通讯的功能,我们只需要在Eclipse或者MyEclipse中写好文章中服务器端的代码,运行起来即可,用accept()方法启动服务器端,等待客户端的连接,在未连接的情况下,服务器端处于堵塞的状态. 二.客户端注意事项 andriod客户端添加网络访问权限 <uses-permission android:name="

unity客户端与c++服务器之间的简单通讯_1

// 服务器 # pragma once using namespace std; # include <iostream> # include <string> # include <stdio.h> # include <winsock2.h> # pragma comment(lib,”ws2_32.lib”) # include “Tool.h” void main() { WSAData wsadata; SOCKET ListeningSocke

Android客户端与Java服务器交互数据(一)SAE服务器搭建

平时大家的测试服务器都是运行在自己的PC上面,用Tomcat或者IIS搭建的本机服务器.其实新浪云平台SinaAppEngine也是挺好用的.今天总结一下我使用过程中的一些小心得: 1.创建SAE应用: 登陆http://sae.sina.com.cn/进行注册,微博帐号可以直接登陆.注册成功后进入"我的首页",控制台>应用管理>创建新应用 然后输入二级域名(应用的唯一标示),应用名称和其他信息,最后选择开发语言,这里以Java为例: JVM级别选择"经济版&qu

Android客户端与Java服务器交互数据(二)阿里云ACE服务器搭建

前段时间写了一个新浪SAE部署代码的小总结,刚好今天阿里云云引擎ACE公测的审核资格通过了,就来对比一下ACE与新浪SAE的使用. 首先是账号,ACE作为阿里产品自然可以通过淘宝账号直接登录,而SAE则可以通过微博账号登录. http://www.aliyun.com/ 阿里云的主营业务比较多,主页很花哨,点击右上角的"管理控制台",然后进入"云引擎ACE",创建应用环境: 这里先写一个简单的JSP工程作为演示,打开Eclipse for JavaEE,然后File

java服务器与c#客户端的字符编码问题

在服务器与客户端交互时,有时候服务器与客户端并不是拿同一种编程语言写的,这时候需要注意字符编码转换的问题.以java服务器和c#客户端为例,此时把c#端接收到的数据用GBK编码表示.  Encoding encoding = Encoding.GetEncoding("GBK");        //定义GBK编码            returnMsg = encoding.GetString(memStream.GetBuffer(), 0, memStream.GetBuffe

JAVA服务器与C#客户端的通信技术调研

JAVA服务器与C#客户端的通信技术调研 研究背景及目的: ARPG项目的需求:需要将现有的服务器从C++的编写平台换为java语言.在对需求进行分析的过程中,发现几点需要研究实现的问题 java与c+语言特性迥异,相比c+ 和c#关系的密切性,java需要对c#风格的一些数据结构和编码格式进行兼容: c#拥有的无符号数据类型如 ushort unint java并不存在,需要对数据类型进行转换: 根据开发需要 客户端现有的通信协议不能更改,所以在java中进行各类型的兼容操作 在项目中底层通信

Java实现IO通信(服务器篇)

Java实现IO通信(服务器篇) 如何利用java实现我们的通信呢?首先我们了解一下什么是通信?通信的机制是怎样的? 首先来讨论一下什么是通信?通信,指人与人或人与自然之间通过某种行为或媒介进行的信息交流与传递,从广义上指需要信息的双方或多方在不违背各自意愿的情况下采用任意方法,任意媒质,将信息从某方准确安全地传送到另方.而这里所说的通信,是在同一局域网内,一个用户给其他用户发送信息的过程. 然后通行的机制是怎么样的呢?这里的JavaIO通信是这样的,首先我们需要一台服务器,并有一个或者多个用户

java服务器与linux c客户端之间udp通信

java服务器和 linux c客户端采用udp协议互相通信,最关键的点是数据结构的统一.比如说,在c中一个char型 是8bit,在java中,char 是16bit,所以c和java的char类型不能直接互相转换.在本例程中,c的char 类型和 java的byte类型,两个数据类型都是8bit,这样就保证了数据正确传输的基本条件之一. java服务器代码如下: import java.io.*; import java.lang.*; import java.net.*; public c