admin管理员组

文章数量:1531762

2024年7月19日发(作者:)

Unity p2p游戏服务器建立、客户端连接和穿透

张昆 QQ: 931076774

GameHost是建立服务器的玩家;

GameClient是加入游戏的玩家;

游戏服务器是C/S模式。

一. 连接类型测试:

GameHost和GameClient在游戏之前,都要进行连接类型测试,来测试自己的NAT类型。

nnection(); 该测试需要连接到Unity ConnectionTester服务器。

如果无法连接ConnectionTester服务器,可以使用blicAddress()代替NAT

类型测试结果,如果没有外网IP,就设置useNat为true。

二. 建立服务器流程:

1. 初始化网络

lizeServer(32, serverPort, useNat);

如果GameHost在内网,需要设置useNat为true;

如果useNat为true,GameHost需要连接Facilitator服务器。

2. 注册服务器

erHost(gameName, UserName, "test123;This is test game!");

注释里面可以增加其它信息,其它地方无法扩展。

3. 结束游戏,注销游戏

sterHost();

三. GameClient进入游戏流程:

1. 发送消息到MasterServer,游戏列表申请

tHostList (gameName);

2. 获取游戏列表数据

stList()

1

if (stList().Length != 0)

{

HostData[] hostData = stList();

int i = 0;

while (i < )

{

("Game name: " + hostData[i].gameName);

i++;

}

ostList();

}

HostData

useNat

gameType

gameName

connectedPlayers

playerLimit

ip

port

passwordProtected

comment

guid

Does this server require NAT punchthrough?

The type of the game (like "MyUniqueGameType")

The name of the game (like John Doe's Game)

Currently connected players

Maximum players limit

Server IP address //注意这里ip是数组

Server port

Does the server require a password?

A miscellaneous comment (can hold data)

The GUID of the host, needed when connecting with NAT punchthrough.

3. 连接某个游戏服务器

t

useNat为false情况下,可以使用下面任意函数连接GameHost(最好用第一个函数)

static function Connect (IPs : string[], remotePort : int, password : string = "") :

NetworkConnectionError

static function Connect (hostData : HostData, password : string = "") : NetworkConnectionError

useNat为true情况下,GameClient需要使用下面函数;此情况下,GameHost和

GameClient都需要连接Facilitator服务器,需要Facilitator存在并正常工作。

static function Connect (GUID : string, password : string = "") : NetworkConnectionError

虽然useNat为true,如果GameHost和GameClient同处一个局域网,GameClient仍旧可

以使用useNat为false的2个函数连接GameHost。

2

另外,Unity提供的MasterServer在代码中强制把NAT信息禁止掉了,如果需要

punchthourgh,需要打开并重新编译。

如果punchthrough不能打通,将使用ProxyServer进行转发,如果没有ProxyServer,

连接失败。

四. 服务器部署

ConnectionTestServer

Facilitator

MasterServer

ProxyServers

Player

ConnectionTester

Facilitator

U10737

U50005

整个系统一台(服务器需要4个Public IP)

5K

ProxyServer

MasterServer

U50110 - U500120 按照RakNet说法,5%用户需要

U23466 1K

Unity的ConnectionTester

:10737

67.225.180.24:10737(可用)

RakNet provides a free one at 8.17.250.34:60481(不可用)

3

本文标签: 服务器连接游戏需要使用