📄 frmserver.cs
字号:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace WindowsApplication1
{
/// <summary>
/// Form1 的摘要说明。
/// </summary>
public class frmServer : System.Windows.Forms.Form
{
private ArrayList clients;
private int listenport;
private TcpListener listener;
private Thread processor;
private Socket clientsocket;
private Thread clientservice;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ListBox lstClients;
private System.Windows.Forms.Button btnExit;
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;
public frmServer()
{
//
// Windows 窗体设计器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
//
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.lstClients = new System.Windows.Forms.ListBox();
this.btnExit = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.label1.Location = new System.Drawing.Point(8, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(144, 16);
this.label1.TabIndex = 0;
this.label1.Text = "现在在线聊天的有:";
//
// lstClients
//
this.lstClients.ItemHeight = 12;
this.lstClients.Location = new System.Drawing.Point(16, 40);
this.lstClients.Name = "lstClients";
this.lstClients.Size = new System.Drawing.Size(256, 184);
this.lstClients.TabIndex = 1;
//
// btnExit
//
this.btnExit.Location = new System.Drawing.Point(192, 240);
this.btnExit.Name = "btnExit";
this.btnExit.TabIndex = 2;
this.btnExit.Text = "退出(&E)";
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// frmServer
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.lstClients);
this.Controls.Add(this.label1);
this.Name = "frmServer";
this.Text = "服务器端聊天程序";
this.Load += new System.EventHandler(this.frmServer_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new frmServer());
}
private void StartListening()
{
listener=new TcpListener(listenport);
listener.Start();
while(true)
{
try
{
Socket s=listener.AcceptSocket();
clientsocket=s;
clientservice=new Thread(new ThreadStart(ServiceClient));
clientservice.Start();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
private void ServiceClient()
{
Socket client=clientsocket;
bool keepalive=true;
while(keepalive)
{
Byte[] buffer=new Byte[1024];
client.Receive(buffer);
string clientcommand=System.Text.Encoding.GetEncoding("gb2312").GetString(buffer);
string[] tokens=clientcommand.Split(new Char[]{'|'});
if(tokens[0]=="CONN")//连接
{
for(int n=0;n<clients.Count;n++)
{
Client cl=(Client)clients[n];
SendToClient(cl,"JOIN|"+tokens[1]);
}
EndPoint ep=client.RemoteEndPoint;
string name=tokens[1].Trim(new Char[]{'\0'});
Client c=new Client(name,ep,clientservice,client);
clients.Add(c);
string message="LIST|"+GetChatterList();
SendToClient(c,message);
lstClients.Items.Add(c.Name+":"+c.Host.ToString());
}
else if(tokens[0].Equals("CHAT"))//聊天
{
for(int n=0;n<clients.Count;n++)
{
Client cl=(Client)clients[n];
SendToClient(cl,clientcommand);
}
}
else if(tokens[0].Equals("PRIV"))//私聊
{
string destclient=tokens[3];
for(int n=0;n<clients.Count;n++)
{
Client cl=(Client)clients[n];
if(cl.Name.CompareTo(tokens[3])==0)
SendToClient(cl,clientcommand);
if(cl.Name.CompareTo(tokens[1])==0)
SendToClient(cl,clientcommand);
}
}
else if(tokens[0].Equals("GONE"))
{
int remove=0;
bool found=false;
int c=clients.Count;
for(int n=0;n<c;n++)
{
Client cl=(Client)clients[n];
SendToClient(cl,clientcommand);
if(cl.Name.CompareTo(tokens[1])==0)
{
remove=n;
found=true;
lstClients.Items.Remove(cl.Name+":"+cl.Host.ToString());
}
}
if(found)
clients.RemoveAt(remove);
client.Close();
keepalive=false;
}
}
}
private void SendToClient(Client cl,string message)
{
try
{
byte[] buffer=System.Text.Encoding.GetEncoding("gb2312").GetBytes(message.Trim(new Char[]{'\0'}).ToCharArray());
cl.Sock.Send(buffer);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
cl.Sock.Close();
cl.CLThread.Abort();
clients.Remove(cl);
lstClients.Items.Remove(cl.Name+":"+cl.Host.ToString());
}
}
private string GetChatterList()
{
string chatters="";
for(int n=0;n<clients.Count;n++)
{
Client cl=(Client)clients[n];
chatters+=cl.Name;
chatters+="|";
}
chatters.Trim(new char[]{'|'});
return chatters;
}
private void frmServer_Load(object sender, System.EventArgs e)
{
listenport=0228;
clients=new ArrayList();
processor=new Thread(new ThreadStart(StartListening));
processor.Start();
}
protected override void OnClosed(EventArgs e)
{
try
{
for(int n=0;n<clients.Count;n++)
{
Client cl=(Client)clients[n];
SendToClient(cl,"QUIT|");
cl.Sock.Close();
cl.CLThread.Abort();
}
listener.Stop();
if(processor!=null)
processor.Abort();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
base.OnClosed(e);
}
private void btnExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -