110,532
社区成员
发帖
与我相关
我的任务
分享
Socket listener;
int listenPort;
public bool isRun;
Type trackStateType = (new TrackStateStr()).GetType();
public ArrayList m_clientSockList = new ArrayList();
Dictionary<string, int> m_IPIndex;
object curAllTrackStateLocker = new object();
public Queue<TrackStateStr> recvTrackStateQueue = new Queue<TrackStateStr>(100);
public ManualResetEvent manualResetEvent = new ManualResetEvent(true);
AutoResetEvent writeHandler = new AutoResetEvent(true);
Thread setTrackTrackThread;
public void initListener()
{
this.listenPort = (int)Port.ServerListenPort;
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(MyIP), this.listenPort);
this.listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.listener.Bind(iep);
this.listener.Listen(16);
this.listener.BeginAccept(new AsyncCallback(OnConnectRequest), this.listener);
this.isRun = true;
}
private void OnConnectRequest(IAsyncResult ar)
{
if (!isRun)
return;
Socket listener = (Socket)ar.AsyncState;
SockChatClient client = new SockChatClient(listener.EndAccept(ar), this);
if (this.IsHandleCreated)
{
int stationIndex = 0;
foreach (KeyValuePair<int, string> kvp in IPArray)
{
if (kvp.Value == ((IPEndPoint)client.Sock.RemoteEndPoint).Address.ToString())
{
stationIndex = kvp.Key;
break;
}
}
if (stationIndex != 0)
{
Invoke(this.m_AddToMsgTips, new string[] { this.stationName[stationIndex] + " 成功连接到服务器" });
client.StationName = this.stationName[stationIndex];
client.StationId = stationIndex;
Invoke(this.m_SetZColor, new object[] { _ZArray[stationIndex], _connectedColor });
m_clientSockList.Add(client);
client.SetupReceiveCallBack();
}
else
{
Invoke(this.m_AddToMsgTips, new string[] { "unknown client join!" });
client.Sock.Close();
//client.StationName = "unknow client";
//client.StationId = 0;
}
}
listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
}
object queueLocker = new object();
public void OnReceiveData(IAsyncResult ar)
{
if (!isRun)
return;
SockChatClient client = (SockChatClient)ar.AsyncState;
byte[] recvData = client.GetReceiveData(ar);
try
{
if (recvData.Length < 1)
{
//收到的字节数为0,远程机器可能已经断开连接
if (this.IsHandleCreated)
{
this.Invoke(this.m_AddToMsgTips, new string[] { "与 " + client.StationName + " 的连接断开" });
if (client.StationId != 0)
{
if (this.stationCtrlState[client.StationId] == 2)
this._twinklingTimerArr[client.StationId].Stop();
this.Invoke(this.m_SetZColor, new object[] { _ZArray[client.StationId], _disconnectedColor });
}
}
this.stationCtrlState[client.StationId] = 0;
client.Sock.Close();
this.m_clientSockList.Remove(client);
return;
}
TrackStateStr newTrackState = (TrackStateStr)this.BytesToStruct(recvData, this.trackStateType);
Invoke(m_AddToMsgTips, new string[] { "from " + client.StationName });
//writeHandler.WaitOne();
lock (queueLocker)
{
recvTrackStateQueue.Enqueue(newTrackState);
}
//writeHandler.Set();
}
catch (Exception er)
{
this.Invoke(this.m_AddToMsgTips, new string[] { er.Message });
}
client.SetupReceiveCallBack();
}
int j = 0;
private void SetTrackStateCall()
{
while (true)
{
manualResetEvent.WaitOne();
//manualResetEvent.Reset();
lock (queueLocker)
{
if (recvTrackStateQueue.Count > 0)
{
try
{
TrackStateStr newTrackState = recvTrackStateQueue.Dequeue();
//更新当前状态
Invoke(m_UpdateCurTrackState, new object[] { newTrackState });
//回发到各个车站
SendBackToCli();
//设置控件状态
Invoke(m_SetTrackState, new object[] { newTrackState });
for (int i = 0; i < 16; i++)
{
this._curAllTrackState.Z[i].modified = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, DateTime.Now + ":From SetTrackStateCall");
}
}
}
//manualResetEvent.Set();
Thread.Sleep(10);
}
}
/// <summary>
/// 回发全线状态到所有客户端
/// </summary>
public void SendBackToCli()
{
byte[] sendData = StructToBytes(this._curAllTrackState);
foreach (SockChatClient cli in this.m_clientSockList)
{
try
{
cli.Sock.Send(sendData);
}
catch
{
cli.Sock.Close();
m_clientSockList.Remove(cli);
//return;
}
}
}
#endregion
class SockChatClient
{
private Socket m_sock;
public Socket Sock
{
get { return m_sock; }
}
private string m_stationName;
public string StationName
{
get { return m_stationName; }
set { m_stationName = value; }
}
private int m_stationId;
public int StationId
{
get { return m_stationId; }
set { m_stationId = value; }
}
private byte[] m_buff;
private int m_bufSize;
ServerForm frmMain;
AsyncCallback receiveData;
public SockChatClient(Socket sock, ServerForm frmMain)
{
this.m_sock = sock;
this.m_bufSize = Marshal.SizeOf((new TrackStateStr()).GetType());
this.frmMain = frmMain;
receiveData = new AsyncCallback(this.frmMain.OnReceiveData);
}
public void SetupReceiveCallBack()
{
try
{
m_buff = null;
m_buff = new byte[m_bufSize];
//AsyncCallback receiveData = new AsyncCallback(frmMain.OnReceiveData);
m_sock.BeginReceive(m_buff, 0, m_buff.Length, SocketFlags.None, receiveData, this);
}
catch (Exception ex)
{
MessageBox.Show("Setup receive callback fail! " + ex.Message, DateTime.Now + ":From Sock " + this.m_stationId + "," + m_stationName);
}
}
public byte[] GetReceiveData(IAsyncResult ar)
{
int nRecvBytes = 0;
try
{
nRecvBytes = m_sock.EndReceive(ar);
}
catch
{
}
byte[] bytesReturn = new byte[nRecvBytes];
Array.Copy(m_buff, bytesReturn, nRecvBytes);
return bytesReturn;
}
}