服務器+客戶端的聊天程序
最近也在接觸SOCKET編程,在當今這樣一個網絡時代,很多技術都以網絡為中心在誕生,至少我認為是這樣的,而SOCKET套接字接口,在實現網絡通訊上處于關鍵地位,所以不會SOCKET是不行的。
首先,本文主要是針對那些剛接觸SOCKET編程的朋友,如果是高手,就可以不看此文啦
在開始之前,我們需要預習一些基礎知識:
什么是SOCKET套接字?
SOCKET通常有那幾種數據格式?
線程的概念?
(以上基本知識我就不講了,網上這方面資料很多的,大家找資料看下吧)
我要介紹的是一個服務器端+客戶端的聊天系統,程序比較簡單,我先把程序運行的界面給大家看下:
上面是服務器端運行界面;下面把客戶端界面貼給大家看下:
功能比較簡單,服務器的端口號可以在“系統菜單”里面的參數配置進行修改的。
看了上面的圖,下面我們就給大家把代碼貼出來:(因為程序比較簡單,所以本人就沒有去分層啦)
服務器端代碼:
- 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;
- using System.Threading;
- using System.Xml;
- namespace Server
- {
- public partial class ServerMain : Form
- {
- public ServerMain()
- {
- InitializeComponent();
- }
- private void ServerMain_Load(object sender, EventArgs e)
- {
- this.CmdStar.Enabled = true;
- this.CmdStop.Enabled = false;
- }
- private void 配置參數ToolStripMenuItem_Click(object sender, EventArgs e)
- {
- Set TSet = new Set();
- TSet.ShowDialog();
- }
- private void 關于ToolStripMenuItem_Click(object sender, EventArgs e)
- {
- About TAbout = new About();
- TAbout.Show();
- }
- /// < summary>
- /// 獲得XML文件中的端口號
- /// < /summary>
- /// < returns>< /returns>
- private int GetPort()
- {
- try
- {
- XmlDocument TDoc = new XmlDocument();
- TDoc.Load("Settings.xml");
- string TPort = TDoc.GetElementsByTagName("ServerPort")[0].InnerXml;
- return Convert.ToInt32(TPort);
- }
- catch { return 6600; }//默認是6600
- }
- //聲明將要用到的類
- private IPEndPoint ServerInfo;//存放服務器的IP和端口信息
- private Socket ServerSocket;//服務端運行的SOCKET
- private Thread ServerThread;//服務端運行的線程
- private Socket[] ClientSocket;//為客戶端建立的SOCKET連接
- private int ClientNumb;//存放客戶端數量
- private byte[] MsgBuffer;//存放消息數據
- private void CmdStar_Click(object sender, EventArgs e)
- {
- ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- ServerInfo=new IPEndPoint(IPAddress.Any,this.GetPort());
- ServerSocket.Bind(ServerInfo);//將SOCKET接口和IP端口綁定
- ServerSocket.Listen(10);//開始監聽,并且掛起數為10
- ClientSocket = new Socket[65535];//為客戶端提供連接個數
- MsgBuffer = new byte[65535];//消息數據大小
- ClientNumb = 0;//數量從0開始統計
- ServerThread = new Thread(RecieveAccept);//將接受客戶端連接的方法委托給線程
- ServerThread.Start();//線程開始運行
- CheckForIllegalCrossThreadCalls = false;//不捕獲對錯誤線程的調用
- this.CmdStar.Enabled = false;
- this.CmdStop.Enabled = true;
- this.StateMsg.Text = "服務正在運行"+" 運行端口:"+this.GetPort().ToString();
- this.ClientList.Items.Add("服務于 " + DateTime.Now.ToString() + " 開始運行.");
- }
- //接受客戶端連接的方法
- private void RecieveAccept()
- {
- while (true)
- {
- ClientSocket[ClientNumb] = ServerSocket.Accept();
- ClientSocket[ClientNumb].BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack),ClientSocket[ClientNumb]);
- this.ClientList.Items.Add(ClientSocket[ClientNumb].RemoteEndPoint.ToString()+" 成功連接服務器.");
- ClientNumb++;
- }
- }
- //回發數據給客戶端
- private void RecieveCallBack(IAsyncResult AR)
- {
- try
- {
- Socket RSocket = (Socket)AR.AsyncState;
- int REnd = RSocket.EndReceive(AR);
- for (int i = 0; i < ClientNumb; i++)
- {
- if (ClientSocket[i].Connected)
- {
- ClientSocket[i].Send(MsgBuffer, 0, REnd,0);
- }
- RSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack), RSocket);
- }
- }
- catch { }
- }
- private void CmdStop_Click(object sender, EventArgs e)
- {
- ServerThread.Abort();//線程終止
- ServerSocket.Close();//關閉SOCKET
- this.CmdStar.Enabled = true;
- this.CmdStop.Enabled = false;
- this.StateMsg.Text = "等待運行";
- this.ClientList.Items.Add("服務于 " + DateTime.Now.ToString() + " 停止運行.");
- }
- }
- }
客戶端代碼:
- 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 Client
- {
- public partial class ClientMain : Form
- {
- public ClientMain()
- {
- InitializeComponent();
- }
- private IPEndPoint ServerInfo;
- private Socket ClientSocket;
- private Byte[] MsgBuffer;
- private Byte[] MsgSend;
- private void ClientMain_Load(object sender, EventArgs e)
- {
- this.CmdSend.Enabled = false;
- this.CmdExit.Enabled = false;
- ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- MsgBuffer = new Byte[65535];
- MsgSend = new Byte[65535];
- CheckForIllegalCrossThreadCalls = false;
- Random TRand=new Random();
- this.UserName.Text = "用戶" + TRand.Next(10000).ToString();
- }
- private void CmdEnter_Click(object sender, EventArgs e)
- {
- ServerInfo = new IPEndPoint(IPAddress.Parse(this.ServerIP.Text), Convert.ToInt32(this.ServerPort.Text));
- try
- {
- ClientSocket.Connect(ServerInfo);
- ClientSocket.Send(Encoding.Unicode.GetBytes("用戶: " + this.UserName.Text + " 進入系統!\n"));
- ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
- this.SysMsg.Text += "登錄服務器成功!\n";
- this.CmdSend.Enabled = true;
- this.CmdEnter.Enabled = false;
- this.CmdExit.Enabled = true;
- }
- catch
- {
- MessageBox.Show("登錄服務器失敗,請確認服務器是否正常工作!");
- }
- }
- private void ReceiveCallBack(IAsyncResult AR)
- {
- try
- {
- int REnd = ClientSocket.EndReceive(AR);
- this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));
- ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
- }
- catch
- {
- MessageBox.Show("已經與服務器斷開連接!");
- this.Close();
- }
- }
- private void CmdSend_Click(object sender, EventArgs e)
- {
- MsgSend = Encoding.Unicode.GetBytes(this.UserName.Text + "說:\n" + this.SendMsg.Text + "\n");
- if (ClientSocket.Connected)
- {
- ClientSocket.Send(MsgSend);
- this.SendMsg.Text = "";
- }
- else
- {
- MessageBox.Show("當前與服務器斷開連接,無法發送信息!");
- }
- }
- private void CmdExit_Click(object sender, EventArgs e)
- {
- if (ClientSocket.Connected)
- {
- ClientSocket.Send(Encoding.Unicode.GetBytes(this.UserName.Text + "離開了房間!\n"));
- ClientSocket.Shutdown(SocketShutdown.Both);
- ClientSocket.Disconnect(false);
- }
- ClientSocket.Close();
- this.CmdSend.Enabled = false;
- this.CmdEnter.Enabled = true;
- this.CmdExit.Enabled = false;
- }
- private void RecieveMsg_TextChanged(object sender, EventArgs e)
- {
- this.RecieveMsg.ScrollToCaret();
- }
- private void SendMsg_KeyDown(object sender, KeyEventArgs e)
- {
- if (e.Control && e.KeyValue == 13)
- {
- e.Handled = true;
- this.CmdSend_Click(this, null);
- }
- }
- }
我只對服務器端的代碼做了注釋,客戶端就沒有寫注釋了,因為代碼是差不多的。區別在于客戶端不需要監聽,也不需要啟用線程進行委托。
關于 ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
這句代碼,我想給初學者解釋一下,這里“AddressFamily.InterNetwork”表示的是使用IPV4地址,“SocketType.Stream”表示使用的是流格式(另外還有數據包格式和原始套接字格式),“ProtocolType.Tcp”表示使用TCP協議(另外還有很多其它協議,例如大家常看到的UDP協議)。
服務器端+客戶端的聊天系統就介紹完了。另外關于SOCKET類中的BeginReceive方法,請大家參考MSDN,里面有詳細說明。
【編輯推薦】