Legacy Documentation: Version 2018.2 (Go to current version)
LanguageEnglish
  • C#

NetworkClient.Connect

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

public void Connect(string serverIp, int serverPort);

Parameters

serverIpTarget IP address or hostname.
serverPortTarget port number.

Description

Connect client to a NetworkServer instance.

Connecting to a server is asynchronous. There is connection message that is fired when the client connects. If the connection fails, a MsgType.Error message will be generated. Once a connection is established you are able to send messages on the connection using NetworkClient.Send(). If using other features of the high level api, the client should call NetworkClient.IsReady() once it is ready to participate in the game. At that point the client will be sent spawned objects and state update messages.

using UnityEngine;
using UnityEngine.Networking;

public class NetClient { NetworkClient myClient;

public void OnConnected(NetworkConnection conn, NetworkReader reader) { Debug.Log("Connected to server"); }

public void OnDisconnected(NetworkConnection conn, NetworkReader reader) { Debug.Log("Disconnected from server"); }

public void OnError(NetworkConnection conn, NetworkReader reader) { SystemErrorMessage errorMsg = reader.SmartRead<SystemErrorMessage>(); Debug.Log("Error connecting with code " + errorMsg.errorCode); }

public void Start() { myClient = NetworkClient.Instance;

myClient.RegisterHandler(MsgType.SYSTEM_CONNECT, OnConnected); myClient.RegisterHandler(MsgType.SYSTEM_DISCONNECT, OnDisconnected); myClient.RegisterHandler(MsgType.SYSTEM_ERROR, OnError);

myClient.Connect("127.0.0.1", 8888); } }

Did you find this page useful? Please give it a rating: