public static int Connect (int hostId, string address, int port, int exeptionConnectionId, out byte error);

参数

hostId与此连接关联的主机 ID(在调用 NetworkTransport.AddHost 时检索)。
address另一个对等方的 IPv4 地址。
port另一个对等方的端口。
exceptionConnectionId如果是默认连接,则设置为 0。
error错误(可以转换为 NetworkError 以便了解更多信息)。

返回

int 成功时的唯一连接标识符(否则为零)。

描述

尝试建立与另一个对等方的连接。

如果发生错误,错误参数将返回一个非零值,该值可以转换为 NetworkError 以便了解更多信息。

即使返回一个非零连接 ID,NetworkTransport.Connect 也仍然有可能失败,因此请务必轮询 NetworkTransport.ReceiveNetworkTransport.ReceiveFromHost 以便监听事件。如果一切正常,则会返回 NetworkEventType.ConnectEvent

using UnityEngine;
using UnityEngine.Networking;

public class ConnectExample : MonoBehaviour { int connectionId; int channelId; int hostId;

void Start() { // Init Transport using default values. NetworkTransport.Init();

// Create a connection config and add a Channel. ConnectionConfig config = new ConnectionConfig(); channelId = config.AddChannel(QosType.Reliable);

// Create a topology based on the connection config. HostTopology topology = new HostTopology(config, 10);

// Create a host based on the topology we just created, and bind the socket to port 12345. hostId = NetworkTransport.AddHost(topology, 12345);

// Connect to the host with IP 10.0.0.42 and port 54321 byte error; connectionId = NetworkTransport.Connect(hostId, "10.0.0.42", 54321, 0, out error); }

void Update() { int outHostId; int outConnectionId; int outChannelId; byte[] buffer = new byte[1024]; int bufferSize = 1024; int receiveSize; byte error;

NetworkEventType evnt = NetworkTransport.Receive(out outHostId, out outConnectionId, out outChannelId, buffer, bufferSize, out receiveSize, out error); switch (evnt) { case NetworkEventType.ConnectEvent: if (outHostId == hostId && outConnectionId == connectionId && (NetworkError)error == NetworkError.Ok) { Debug.Log("Connected"); } break; case NetworkEventType.DisconnectEvent: if (outHostId == hostId && outConnectionId == connectionId) { Debug.Log("Connected, error:" + error.ToString()); } break; } } }