83 lines
1.7 KiB
C#
83 lines
1.7 KiB
C#
using System.Collections;
|
|
using Firesplash.UnityAssets.SocketIO;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
public class PingPongClientSample : MonoBehaviour
|
|
{
|
|
public Text txtSID;
|
|
|
|
public Text txtPing;
|
|
|
|
public Text txtPong;
|
|
|
|
public Text txtLosses;
|
|
|
|
public Text txtDC;
|
|
|
|
private SocketIOCommunicator sioCom;
|
|
|
|
private int pings;
|
|
|
|
private int pongs;
|
|
|
|
private int losses;
|
|
|
|
private int dcs;
|
|
|
|
private bool pongReceived;
|
|
|
|
private void Start()
|
|
{
|
|
sioCom = GetComponent<SocketIOCommunicator>();
|
|
sioCom.Instance.On("connect", delegate
|
|
{
|
|
Debug.Log("Connected! Socket ID: " + sioCom.Instance.SocketID);
|
|
txtSID.text = "SocketID: " + sioCom.Instance.SocketID;
|
|
});
|
|
sioCom.Instance.On("disconnect", delegate(string payload)
|
|
{
|
|
Debug.LogWarning("Disconnected: " + payload);
|
|
Text text = txtDC;
|
|
int num = ++dcs;
|
|
text.text = "Disconnects: " + num;
|
|
txtSID.text = "SocketID: <i>lost connection to server</i>";
|
|
});
|
|
sioCom.Instance.On("PONG", delegate(string seqno)
|
|
{
|
|
if (int.Parse(seqno) != pings)
|
|
{
|
|
Debug.LogWarning("Received PONG with SeqNo " + seqno + " out of order. Ignoring.");
|
|
}
|
|
else
|
|
{
|
|
pongReceived = true;
|
|
Text text = txtPong;
|
|
int num = ++pongs;
|
|
text.text = "PONGs sent: " + num;
|
|
}
|
|
});
|
|
sioCom.Instance.Connect();
|
|
StartCoroutine(Pinger());
|
|
}
|
|
|
|
private IEnumerator Pinger()
|
|
{
|
|
while (true)
|
|
{
|
|
yield return new WaitUntil(() => sioCom.Instance.IsConnected());
|
|
pongReceived = false;
|
|
SocketIOInstance instance = sioCom.Instance;
|
|
int num = ++pings;
|
|
instance.Emit("PING", num.ToString(), DataIsPlainText: true);
|
|
txtPing.text = "PINGs sent: " + pings;
|
|
yield return new WaitForSeconds(3f);
|
|
if (!pongReceived)
|
|
{
|
|
losses++;
|
|
txtLosses.text = "Losses: " + losses;
|
|
}
|
|
}
|
|
}
|
|
}
|