Skip to content

Instantly share code, notes, and snippets.

@kirillrybin
Forked from heartgamer/SimpleChat.cs
Created June 26, 2019 14:23
Show Gist options
  • Save kirillrybin/041e1893c8a8fef4a666de861bd0cd44 to your computer and use it in GitHub Desktop.
Save kirillrybin/041e1893c8a8fef4a666de861bd0cd44 to your computer and use it in GitHub Desktop.
BEST HTTP socket.io example.
using UnityEngine;
using System.Collections;
using System;
using BestHTTP;
using BestHTTP.SocketIO;
public class SimpleChat : MonoBehaviour {
public UILabel lblChatMessages;
//public string strName;
//public string strRoom;
SocketManager manager;
public void ConnectToChat()
{
SocketOptions options = new SocketOptions();
options.AutoConnect = false;
manager = new SocketManager(new Uri("http://localhost:4000/socket.io/"), options);
//Socket sockChat = manager.GetSocket("/socket.io");
//manager.Socket.On(SocketIOEventTypes.Error, (socket, packet, args) => Debug.LogError(string.Format("Error: {0}", args[0].ToString())));
manager.Socket.On(SocketIOEventTypes.Connect, OnServerConnect);
manager.Socket.On(SocketIOEventTypes.Disconnect, OnServerDisconnect);
manager.Socket.On(SocketIOEventTypes.Error, OnError);
manager.Socket.On("reconnect", OnReconnect);
manager.Socket.On("reconnecting", OnReconnecting);
manager.Socket.On("reconnect_attempt", OnReconnectAttempt);
manager.Socket.On("reconnect_failed", OnReconnectFailed);
manager.Socket.On("chat message", OnChatMessage);
manager.Open();
}
public void SendChatMessage()
{
manager.Socket.Emit("chat message", "hello!!!");
}
public void SendTimerMessage()
{
manager.Socket.Emit("timer", "12321312");
}
void OnChatMessage(Socket socket, Packet packet, params object[] args)
{
Debug.Log("OnChatMessage : " + args[0].ToString() );
}
void Awake()
{
}
void Start()
{
//ConnectToChat();
}
void OnDestroy()
{
manager.Close();
}
void OnServerConnect(Socket socket, Packet packet, params object[] args)
{
Debug.Log("Connected");
}
void OnServerDisconnect(Socket socket, Packet packet, params object[] args)
{
Debug.Log("Disconnected");
}
void OnError(Socket socket, Packet packet, params object[] args)
{
Error error = args[0] as Error;
switch(error.Code)
{
case SocketIOErrors.User:
Debug.LogWarning("Exception in an event handler!");
break;
case SocketIOErrors.Internal:
Debug.LogWarning("Internal error!");
break;
default:
Debug.LogWarning("server error!");
break;
}
}
void OnReconnect(Socket socket, Packet packet, params object[] args)
{
Debug.Log("Reconnected");
}
void OnReconnecting(Socket socket, Packet packet, params object[] args)
{
Debug.Log("Reconnecting");
}
void OnReconnectAttempt(Socket socket, Packet packet, params object[] args)
{
Debug.Log("ReconnectAttempt");
}
void OnReconnectFailed(Socket socket, Packet packet, params object[] args)
{
Debug.Log("ReconnectFailed");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment