📄 form1.cs
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace GRRSServer
{
delegate void SetItemToCtrlDelegate(string strInfo);
public partial class Form1 : Form
{
private System.Collections.Generic.List<ConnectionManager> clients;
private ConnectionManager connMgr=null;
private BackgroundWorker bwListener;
private Socket listenerSocket;
private IPAddress serverIP;
private int serverPort;
private bool bListen = true;
public Form1()
{
//connMgr=new ConnectionManager()
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
bListen = true;
clients = new List<ConnectionManager>();
serverPort = 6000;
serverIP = IPAddress.Any;
bwListener = new BackgroundWorker();
bwListener.WorkerSupportsCancellation = true;
bwListener.DoWork += new DoWorkEventHandler(StartToListen);
bwListener.RunWorkerAsync();
string strInfo = string.Format("*** Listening on port {0}{1}{2} started.Press ENTER to shutdown server. ***\n", serverIP.ToString(), ":", serverPort.ToString());
this.listBox1.Items.Add(strInfo);
}
private void StartToListen(object sender, DoWorkEventArgs e)
{
try
{
this.listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.listenerSocket.Bind(new IPEndPoint(this.serverIP, this.serverPort));
this.listenerSocket.Listen(200);
while (bListen)
this.CreateNewClientManager(this.listenerSocket.Accept());
}
catch(SocketException ex)
{
if (ex.ErrorCode == 10004)
return;
else
{
throw ex;
}
}
}
private void CreateNewClientManager(Socket socket)
{
ConnectionManager newClientManager = new ConnectionManager(socket);
newClientManager.ClientReceived += new ClientReceivedEventHandler(CommandReceived);
newClientManager.Disconnected += new DisconnectedEventHandler(ClientDisconnected);
//newClientManager.CommandSent += new CommandSentEventHandler(newClientManager_CommandSent);
//newClientManager.CommandFailed += new CommandSendingFailedEventHandler(newClientManager_CommandFailed);
this.CheckForAbnormalDC(newClientManager);
this.clients.Add(newClientManager);
string strInfo = string.Format("Connected.{0}:{1}\r\n", newClientManager.IP, newClientManager.Port);
this.Invoke(new SetItemToCtrlDelegate(AddString), strInfo);
}
void newClientManager_CommandFailed(object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}
void newClientManager_CommandSent(object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}
private void AddString(string strInfo)
{
this.listBox1.Items.Add(strInfo);
}
private void CheckForAbnormalDC(ConnectionManager mngr)
{
if (this.RemoveClientManager(mngr.IP))
{
string strInfo = string.Format("DisConnected.{0}:{1}\r\n", mngr.IP, mngr.Port);
this.Invoke(new SetItemToCtrlDelegate(AddString), strInfo);
}
}
void ClientDisconnected(object sender, ClientEventArgs e)
{
if (this.RemoveClientManager(e.IP))
{
string strInfo = string.Format("Disconnected.{0}:{1}\r\n", e.IP, e.Port);
this.Invoke(new SetItemToCtrlDelegate(AddString), strInfo);
}
}
private bool RemoveClientManager(IPAddress ip)
{
lock (this)
{
int index = this.IndexOfClient(ip);
if (index != -1)
{
string name = this.clients[index].ClientName;
this.clients.RemoveAt(index);
//Inform all clients that a client had been disconnected.
//Command cmd = new Command(CommandType.ClientLogOffInform, IPAddress.Broadcast);
//cmd.SenderName = name;
//cmd.SenderIP = ip;
//this.BroadCastCommand(cmd);
return true;
}
return false;
}
}
private int IndexOfClient(IPAddress ip)
{
int index = -1;
foreach (ConnectionManager cMngr in this.clients)
{
index++;
if (cMngr.IP.Equals(ip))
return index;
}
return -1;
}
private void CommandReceived(object sender, ClientEventArgs e)
{
int index = this.IndexOfClient(e.IP);
string name=string.Empty;
if (index != -1)
{
name = this.clients[index].ClientName;
}
string str = string.Format("{3}(IP {0}:{1})===>\r\n{2}", e.IP, e.Port, e.ReceivedString,name);
this.Invoke(new SetItemToCtrlDelegate(AddString), str);
}
public void DisconnectServer()
{
try
{
if (this.clients != null)
{
foreach (ConnectionManager mngr in this.clients)
{
mngr.Disconnect();
}
bListen = false;
this.bwListener.CancelAsync();
this.bwListener.Dispose();
this.listenerSocket.Close();
GC.Collect();
string strInfo = string.Format("*** The Server have Stopped Listening on the port {0}{1}{2} ***\n", serverIP.ToString(), ":", serverPort.ToString());
this.listBox1.Items.Add(strInfo);
}
}
catch(SocketException e)
{
int errorcode = e.ErrorCode;
//throw e;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnSend_Click(object sender, EventArgs e)
{
if (this.clients != null&&this.clients.Count>0)
{
foreach (ConnectionManager cMngr in this.clients)
{
Command comm = new Command(CommandType.CommonUserMsg, cMngr.IP);
comm.SenderIP = IPAddress.Any;
comm.SenderName = "server";
comm.MetaData = "可以收工了";
cMngr.SendCommand(comm);
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
DisconnectServer();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -