static string IP = "127.0.0.1";
static int Port = 10010;
public static List ClientInfos = new List();
private void Start()
{
TcpServer = new TcpSocketServer(IP, Port);
TcpServer.Initialized();
TcpServer.OnConnection += OnConnection;
TcpServer.OnReceive += OnReceive;
TcpServer.OnClientQuit += OnClientQuit;
TcpServer.OnDisconnected += OnDisconnected;
TcpServer.Connection();
}
///
/// 监听客户端连接
///
///
void OnConnection(ClientInfo info)
{
string msg = "客户端 " + info.id + " 加入会话!";
Debug.Log(msg);
OnSendAllMsg(msg);
ClientInfos.Add(info);
GameManager.Instence.AddDropdownOptionData(info.id);
}
///
/// 监听接收客户端消息
///
///
///
void OnReceive(ClientInfo info, string msg)
{
Debug.Log("接收到客户端 " + info.id + " 消息: " + msg);
GameManager.Instence.textMessage= info.id + ": " + msg;
}
///
/// 监听客户端退出
///
///
void OnClientQuit(ClientInfo info)
{
Debug.Log("客户端 " + info.id + " 退出会话!");
ClientInfos.Remove(info);
GameManager.Instence.RemoveDropdownOptionData(info.id);
}
///
/// 服务器关闭
///
void OnDisconnected()
{
Debug.Log("服务端关闭!");
}
///
/// 群发消息
///
public static void OnSendAllMsg(string resMsg)
{
TcpServer.sendAllMsg(resMsg);
}
///
/// 发送消息给客户端
///
///
///
public static bool OnSendToClient(string idName, string resMsg)
{
bool state = false;
for (int i = 0; i < ClientInfos.Count; i++)
{
ClientInfo info = ClientInfos[i];
if (idName == info.id)
{
Socket socket = ClientInfos[i].socket;
TcpServer.Send(socket, resMsg);
state = true;
break;
}
}
return state;
}
private void OnDestroy()
{
if(TcpServer != null) TcpServer.Close();
}
private void OnApplicationQuit()
{
if(TcpServer != null) TcpServer.Close();
}