Skip to content

Instantly share code, notes, and snippets.

@sunho
Created February 5, 2019 06:50
Show Gist options
  • Save sunho/b14cbbfe938b13fdefbb32af696e1c77 to your computer and use it in GitHub Desktop.
Save sunho/b14cbbfe938b13fdefbb32af696e1c77 to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using Game.Events;
using Models;
using Newtonsoft.Json;
using UnityEngine;
namespace Network
{
public class GameServer : MonoBehaviour
{
public static GameServer instance;
//socket
private SocketClient asyncCallbackClient = new SocketClient();
//event
private JsonSerializerSettings eventJsonSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
};
public delegate void GameEventHandler(Game.Events.Event e);
private Dictionary<Type, List<GameEventHandler>> handlers = new Dictionary<Type, List<GameEventHandler>>();
private void Awake()
{
//singleton
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
eventJsonSettings.Converters.Add(new EventConverter());
InitHandlers();
}
private void Update()
{
int dataCount = asyncCallbackClient.dataQueue.Count;
if (dataCount > 0)
{
for (int i = 0; i < dataCount; i++)
{
string data = asyncCallbackClient.dataQueue.Dequeue();
ReceiveEvent(data);
}
}
int logCount = asyncCallbackClient.logQueue.Count;
if (logCount > 0)
{
for (int i = 0; i < logCount; i++)
{
Debug.Log(asyncCallbackClient.logQueue.Dequeue());
}
}
}
private void Connect(string ip, int port, Action callback)
{
if (asyncCallbackClient.state == ClientState.DISCONNECTED)
asyncCallbackClient.Connect(ip, port, callback);
else Debug.Log($"[AsyncCallbackClient]Already Connected {ip}:{port}");
}
private void ReceiveEvent(string data)
{
foreach (string splitedStr in data.Split('\n'))
{
if (splitedStr == "")
return;
Game.Events.Event e = JsonConvert.DeserializeObject<Game.Events.Event>(splitedStr, eventJsonSettings);
Debug.Log(e.GetType());
foreach(var handle in handlers[e.GetType()])
{
handle(e);
}
}
}
public void EndConnection()
{
ClearHandles();
asyncCallbackClient.Close();
}
public void ClearHandles()
{
handlers.Clear();
}
public void SendCommand(Command command)
{
string json = JsonConvert.SerializeObject(command);
asyncCallbackClient.SendData(json + "\n");
}
public void AddHandler<T>(GameEventHandler handler)
{
Type type = typeof(T);
if(!handlers.ContainsKey(type))
{
handlers[type] = new List<GameEventHandler>();
}
handlers[type].Add(handler);
}
public void RemoveHandler<T>(GameEventHandler handler)
{
Type type = typeof(T);
handlers[type].Remove(handler);
}
public void ExitGame()
{
asyncCallbackClient.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment