using Google.Protobuf.WellKnownTypes;
using JiangsuEarthquake.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace JiangsuEarthquake.Models
{
public class ServerModel : NotifyBase
{
SocketInfo SI = new SocketInfo();
private LowerComputerModel lowerComputerModel { get; set; } = new LowerComputerModel();
public Server _server { get; set; } = new Server();
private bool isOpened = false;
///
/// 服务器是否开启
///
public bool IsOpened
{
get { return isOpened; }
set { isOpened = value; this.DoNotify(); }
}
///
/// 启动服务器
///
///
///
public bool DoStart(SocketInfo socketInfo)
{
SI.IP = socketInfo.IP;
SI.Port = socketInfo.Port;
try
{
_server.InitSocket(socketInfo.IP, socketInfo.Port); //初始化设备的IP和端口号
IsOpened = _server.Start();
if (IsOpened)
{
_server.pushSockets = ReceiveMess;
}
return IsOpened;
}
catch
{
IsOpened = false;
return IsOpened;
}
}
///
/// 停止服务器
///
public bool DoStop()
{
_server.Stop();
IsOpened = false;
return IsOpened;
}
///
/// 委托刷新客户数据
///
private void ReceiveMess(Sockets sks)
{
if (sks.ex != null)
{
//在此处理异常信息
if (sks.ClientDispose)
{
//客户端非主动断开连接下线. 非正常下线
if (sks.Ip != null)
{
_server.ClientList.Remove(sks);
}
}
}
else
{
if (sks.Offset == 0)
{
//正常是不会发送0包的,只有客户端主动断开连接时发送空包.
//客户端下线.
_server.ClientList.Remove(sks);
}
else if (sks.NewClientFlag)
{
_server.ClientList.Add(sks);
}
else
{
//接收客户端消息
byte[] buffer = new byte[sks.Offset];
Array.Copy(sks.RecBuffer, buffer, sks.Offset);
try
{
int stationName = 0;
if (SI.Port == int.Parse(Tools.GetAppSetting("XWJ_Service_Port1"))&& SI.IP == Tools.GetAppSetting("XWJ_Service_IP1"))
{
stationName = 1;
}
else if (SI.Port == int.Parse(Tools.GetAppSetting("XWJ_Service_Port2")) && SI.IP == Tools.GetAppSetting("XWJ_Service_IP2"))
{
stationName = 2;
}
lowerComputerModel.ParsingData(new List(buffer), stationName);
}
catch (Exception ex)
{
return;
}
}
}
}
///
/// 发送消息给客户端
///
public void SendToClient(IPEndPoint ip, byte[] SendData)
{
Task.Factory.StartNew(new Action(() =>
{
Thread.Sleep(1000);
_server.SendToClient(ip, SendData);
}));
}
///
/// 推送消息
///
public void SendMess(byte[] SendData)
{
Task.Factory.StartNew(new Action(() =>
{
_server.SendToAll(SendData);
}));
}
}
}