?? chatserver.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 ChatServer
{
public class ClientSeverForm : System.Windows.Forms.Form
{
/// <summary>
/// 必需的設計器變量。
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.GroupBox grpSocket;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox tbSocketPort;
private System.Windows.Forms.TextBox tbSocketClientsNum;
private System.Windows.Forms.RichTextBox rtbSocketMsg;
private System.Windows.Forms.Button btnSocketStart;
private System.Windows.Forms.Button btnSocketStop;
private System.Windows.Forms.ListBox lbSocketClients;
//clients數組保存當前在線用戶的Client對象
internal static Hashtable clients=new Hashtable();
//該服務器默認的監聽的端口號
private TcpListener listener;
//服務器可以支持的最多的客戶端的連接數
static int MAX_NUM=100;
//開始服務的標志
internal static bool SocketServiceFlag = false;
public ClientSeverForm()
{
//
// Windows 窗體設計器支持所必需的
//
InitializeComponent();
//
// TODO: 在 InitializeComponent 調用后添加任何構造函數代碼
//
}
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ClientSeverForm));
this.grpSocket = new System.Windows.Forms.GroupBox();
this.lbSocketClients = new System.Windows.Forms.ListBox();
this.btnSocketStop = new System.Windows.Forms.Button();
this.rtbSocketMsg = new System.Windows.Forms.RichTextBox();
this.btnSocketStart = new System.Windows.Forms.Button();
this.tbSocketPort = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.tbSocketClientsNum = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.grpSocket.SuspendLayout();
this.SuspendLayout();
//
// grpSocket
//
this.grpSocket.Controls.Add(this.lbSocketClients);
this.grpSocket.Controls.Add(this.btnSocketStop);
this.grpSocket.Controls.Add(this.rtbSocketMsg);
this.grpSocket.Controls.Add(this.btnSocketStart);
this.grpSocket.Controls.Add(this.tbSocketPort);
this.grpSocket.Controls.Add(this.label1);
this.grpSocket.Controls.Add(this.tbSocketClientsNum);
this.grpSocket.Controls.Add(this.label3);
this.grpSocket.Location = new System.Drawing.Point(16, 16);
this.grpSocket.Name = "grpSocket";
this.grpSocket.Size = new System.Drawing.Size(784, 368);
this.grpSocket.TabIndex = 13;
this.grpSocket.TabStop = false;
this.grpSocket.Text = "Socket連接監聽";
//
// lbSocketClients
//
this.lbSocketClients.Location = new System.Drawing.Point(8, 64);
this.lbSocketClients.Name = "lbSocketClients";
this.lbSocketClients.ScrollAlwaysVisible = true;
this.lbSocketClients.Size = new System.Drawing.Size(200, 290);
this.lbSocketClients.TabIndex = 21;
//
// btnSocketStop
//
this.btnSocketStop.Enabled = false;
this.btnSocketStop.Location = new System.Drawing.Point(528, 32);
this.btnSocketStop.Name = "btnSocketStop";
this.btnSocketStop.Size = new System.Drawing.Size(88, 24);
this.btnSocketStop.TabIndex = 20;
this.btnSocketStop.Text = "Socket停止";
this.btnSocketStop.Click += new System.EventHandler(this.btnSocketStop_Click);
//
// rtbSocketMsg
//
this.rtbSocketMsg.Location = new System.Drawing.Point(216, 64);
this.rtbSocketMsg.Name = "rtbSocketMsg";
this.rtbSocketMsg.Size = new System.Drawing.Size(552, 296);
this.rtbSocketMsg.TabIndex = 19;
this.rtbSocketMsg.Text = "";
//
// btnSocketStart
//
this.btnSocketStart.Location = new System.Drawing.Point(424, 32);
this.btnSocketStart.Name = "btnSocketStart";
this.btnSocketStart.Size = new System.Drawing.Size(88, 24);
this.btnSocketStart.TabIndex = 18;
this.btnSocketStart.Text = "Socket啟動";
this.btnSocketStart.Click += new System.EventHandler(this.btnSocketStart_Click);
//
// tbSocketPort
//
this.tbSocketPort.Location = new System.Drawing.Point(328, 32);
this.tbSocketPort.Name = "tbSocketPort";
this.tbSocketPort.Size = new System.Drawing.Size(83, 20);
this.tbSocketPort.TabIndex = 17;
this.tbSocketPort.Text = "1234";
this.tbSocketPort.TextChanged += new System.EventHandler(this.tbSocketPort_TextChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(232, 31);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 21);
this.label1.TabIndex = 16;
this.label1.Text = "Socket端口號:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// tbSocketClientsNum
//
this.tbSocketClientsNum.Location = new System.Drawing.Point(112, 32);
this.tbSocketClientsNum.Name = "tbSocketClientsNum";
this.tbSocketClientsNum.ReadOnly = true;
this.tbSocketClientsNum.TabIndex = 15;
this.tbSocketClientsNum.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 36);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(97, 16);
this.label3.TabIndex = 13;
this.label3.Text = "當前在線用戶:";
//
// ClientSeverForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(818, 407);
this.Controls.Add(this.grpSocket);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimizeBox = false;
this.Name = "ClientSeverForm";
this.Text = "聊天室服務器";
this.Closing += new System.ComponentModel.CancelEventHandler(this.ClientSeverForm_Closing);
this.grpSocket.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new ClientSeverForm());
}
private string getIPAddress()
{
// 獲得本機局域網IP地址
IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if (AddressList.Length<1)
{
return "";
}
return AddressList[0].ToString();
}
private static string getDynamicIPAddress( )
{
// 獲得撥號動態分配IP地址
IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;
if (AddressList.Length<2)
{
return "";
}
return AddressList[1].ToString();
}
private int getValidPort(string port)
{
int lport;
//測試端口號是否有效
try
{
//是否為空
if (port=="")
{
throw new ArgumentException(
"端口號為空,不能啟動服務器");
}
lport = System.Convert.ToInt32(port);
}
catch (Exception e)
{
//ArgumentException,
//FormatException,
//OverflowException
Console.WriteLine("無效的端口號:" + e.ToString());
this.rtbSocketMsg.AppendText("無效的端口號:" + e.ToString()+"\n");
return -1;
}
return lport;
}
//當單擊“Socket啟動”按鈕時,便開始監聽指定的Socket端口
private void btnSocketStart_Click(object sender, System.EventArgs e)
{
int port = getValidPort(tbSocketPort.Text);
if (port<0)
{
return;
}
string ip = this.getIPAddress();
try
{
IPAddress ipAdd=IPAddress.Parse(ip);
//創建服務器套接字
listener=new TcpListener(ipAdd, port);
//開始監聽服務器端口
listener.Start();
this.rtbSocketMsg.AppendText("Socket服務器已經啟動,正在監聽" +
ip + " 端口號:" + this.tbSocketPort.Text + "\n");
//啟動一個新的線程,執行方法this.StartSocketListen,
//以便在一個獨立的進程中執行確認與客戶端Socket連接的操作
ClientSeverForm.SocketServiceFlag = true;
Thread thread=new Thread(new ThreadStart(this.StartSocketListen));
thread.Start();
this.btnSocketStart.Enabled = false;
this.btnSocketStop.Enabled = true;
}
catch(Exception ex)
{
this.rtbSocketMsg.AppendText(ex.Message.ToString()+"\n");
}
}
//在新的線程中的操作,它主要用于當接收到一個客戶端請求時,確認與客戶端的連接,
//并且立刻啟動一個新的線程來處理和該客戶端的信息交互。
private void StartSocketListen()
{
while(ClientSeverForm.SocketServiceFlag)
{
try
{
//當接收到一個客戶端請求時,確認與客戶端的連接
if (listener.Pending())
{
Socket socket=listener.AcceptSocket();
if(clients.Count>=MAX_NUM)
{
this.rtbSocketMsg.AppendText("已經達到了最大連接數:" +
MAX_NUM + ",拒絕新的連接\n");
socket.Close();
}
else
{
//啟動一個新的線程,
//執行方法this.ServiceClient,處理用戶相應的請求
Client client = new Client(this, socket);
Thread clientService=new Thread(
new ThreadStart(client.ServiceClient));
clientService.Start();
}
}
Thread.Sleep(200);
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -