Skip to content

Basic client application: Unity

maxless edited this page Nov 18, 2016 · 1 revision

Basic client application: Unity

This tutorial is based on the Minimal project. It describes how to make a basic client application that can communicate with the Snipe server.

First you will need to create a new C# script. Include needed namespaces:

	using MiniIT;
	using MiniIT.Snipe;

Now define a SnipeClient variable:

	private SnipeClient mClient;

Initialize it in the Start method:

	// Creating client
	mClient = SnipeClient.Instance;
	
	// Adding events listeners
	mClient.ConnectionSucceeded += OnConnected;
	mClient.ConnectionFailed += OnConnectionFailed;
	mClient.ConnectionLost += OnConnectionLost;
	mClient.DataReceived += OnServerResponse;

After that you will be able to initiate a connection to the server:

	const string SERVER_HOST = "192.168.0.100";
	const int    SERVER_PORT = 2501;
	
	mClient.Connect(SERVER_HOST, SERVER_PORT);  // connect using TCP Client

Alternatively, if you need to use the WebSocket connection, call mClient.ConnectWebSocket instead of mClient.Connect:

	mClient.ConnectWebSocket(SERVER_HOST, SERVER_PORT);    // connect using WebSocket

You can also call mClient.ConnectWebSocket with a single string path:

	mClient.ConnectWebSocket("ws://192.168.0.100:2501/");  // connect using WebSocket

The next step is defining event handlers:

	void OnConnected (DataEventArgs e)
	{
		Debug.Log("Connected successfully");
		
		// Do something
		// ...
	}

	void OnConnectionFailed (DataEventArgs e)
	{
		Debug.Log("Connection failed");
		
		// Do something
		// ...
	}

	void OnConnectionLost (DataEventArgs e)
	{
		Debug.Log("Connection lost");
		
		// Do something
		// ...
	}

After the application connects to the server you may communicate with it through the mClient.SendRequest method. For example, you can send a user login request:

	void OnConnected (DataEventArgs e)
	{
		Debug.Log("Connected successfully");
		
		// trying to send request
		ExpandoObject parameters = new ExpandoObject();
		parameters["name"] = "testname";
		parameters["password"] = "";
		mClient.SendRequest("user.login", parameters);
	}

You should handle server responses in the DataReceived event handler. In our example this is the OnServerResponse method:

	void OnServerResponse (DataEventArgs e)
	{
		Debug.Log("Server says: " + e.Data.ToJSONString());
	}

DataEventArgs class has Data property which is an instance of ExpandoObject class that contains the parsed server response.

This should be enough to get you started on writing a full client application.

You may download this example project here.

Clone this wiki locally