仿百度网盘,ftp上传下载文件,仿qq群聊,加入群组,socket技术聊天System.Timers.Timer timer = new System.Timers.Timer() { Interval = 1000, Enabled = true };
/// <summary>
/// 初始加载连接
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FrmServerMain_Load(object sender, EventArgs e)
{
timer.Elapsed = (a,b) =>
{
barTimeDate.Caption = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
};
timer.Start();
try
{
if (serverSocket != null)
{
serverSocket.Close();
thStartListen.Abort(); //将监听进程关掉
foreach (var socket in clientList.Values)
{
socket.Close();
}
clientList.Clear();
serverSocket = null;
isListen = false;
barStaticItem1.Caption = "服务已停止...";
}
else
{
isListen = true;
clientList = new Dictionary<string, Socket>();
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
endPoint = new IPEndPoint(ipadr, 8080);
try
{
serverSocket.Bind(endPoint);
serverSocket.Listen(100);
thStartListen = new Thread(StartListen);
thStartListen.IsBackground = true;
thStartListen.Start();
barStaticItem1.Caption = "服务已开启...";
}
catch (Exception eg)
{
if (serverSocket != null)
{
serverSocket.Close();
thStartListen.Abort(); //将监听进程关掉
foreach (var socket in clientList.Values)
{
socket.Close();
}
clientList.Clear();
serverSocket = null;
isListen = false;
barStaticItem1.Caption = "服务已停止...";
}
}
}
}
catch (SocketException ep)
{
if (serverSocket != null)
{
serverSocket.Close();
thStartListen.Abort(); //将监听进程关掉
foreach (var socket in clientList.Values)
{
socket.Close();
}
clientList.Clear();
serverSocket = null;
isListen = false;
barStaticItem1.Caption = "服务已停止...";
}
}
}
评论