-2

我正在开发一款免费版 Unity 中的 android MMO android 游戏。我的电脑上安装了 node.js。我应该使用以下服务器客户端代码吗,因为当我尝试测试它时,我可以让服务器端脚本运行,但无法确定客户端是否正在连接。此外,当我尝试构建 apk 时,unity 会出现错误提示“使用 System.Net.Sockets 需要专业版的 unity”。请帮忙!!

服务器端 (在 node.js 上)

`var net = require('net');
var tcp_server = net.createServer(function(socket)
{

    socket.write('hello\n');
    socket.end('world\n');
});
tcp_server.listen(8000);
console.log("Server Running...");`

客户端(在统一 c# 脚本中)

`using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Text;
public class tcpClient : MonoBehaviour 
{
    static void Main(string[] args)
    {
        Debug.Log("start");
        TcpClient tcpClient = new TcpClient();
        tcpClient.Connect("127.0.0.1", 8000);
        Debug.Log ("Connected");
        NetworkStream clientStream = tcpClient.GetStream();
        byte[] message = new byte[4096];
        int bytesRead;
        bytesRead = 0;

        try
        {
            // Read up to 4096 bytes
            bytesRead = clientStream.Read(message, 0, 4096);
        }
        catch
        {
            /*a socket error has occured*/
        }
        //We have read the message.
        ASCIIEncoding encoder = new ASCIIEncoding();
        Debug.Log(encoder.GetString(message, 0, bytesRead));
        //Console.WriteLine(encoder.GetString(message, 0, bytesRead));
        tcpClient.Close();
    }
}`
4

2 回答 2

0

首先,如果你想使用原生套接字,你需要 Unity3D Pro。

但是还有另一种方法可以处理这个问题。

您可以使用其中之一。您可以在 Unity Asset Store 中找到它们。(我知道这些可能比这些资产更多)。(它们不是免费的,但比 Unity pro 便宜)。

  1. 不错的插座
  2. 最佳 HTTP 基础
  3. 最佳 HTTP 专业版

在那之后@ploutch 提到了 Socket.IO。真的很棒。

但是不要忘记 Unity3D 有它自己的Network。您可以创建服务器也可以使用它加入客户端。还有一些非常好的供应商,并为您提供了额外的选择。

喜欢:

  1. 光子统一网络
  2. Bolt 网络中间件
于 2015-01-20T11:55:53.983 回答
0

最简单的方法可能是使用 socket.io

http://socket.io/get-started/

于 2014-09-24T07:36:08.940 回答