服務(wù)器+客戶(hù)端的聊天程序
最近也在接觸SOCKET編程,在當(dāng)今這樣一個(gè)網(wǎng)絡(luò)時(shí)代,很多技術(shù)都以網(wǎng)絡(luò)為中心在誕生,至少我認(rèn)為是這樣的,而SOCKET套接字接口,在實(shí)現(xiàn)網(wǎng)絡(luò)通訊上處于關(guān)鍵地位,所以不會(huì)SOCKET是不行的。
首先,本文主要是針對(duì)那些剛接觸SOCKET編程的朋友,如果是高手,就可以不看此文啦
在開(kāi)始之前,我們需要預(yù)習(xí)一些基礎(chǔ)知識(shí):
什么是SOCKET套接字?
SOCKET通常有那幾種數(shù)據(jù)格式?
線程的概念?
(以上基本知識(shí)我就不講了,網(wǎng)上這方面資料很多的,大家找資料看下吧)
我要介紹的是一個(gè)服務(wù)器端+客戶(hù)端的聊天系統(tǒng),程序比較簡(jiǎn)單,我先把程序運(yùn)行的界面給大家看下:
上面是服務(wù)器端運(yùn)行界面;下面把客戶(hù)端界面貼給大家看下:
功能比較簡(jiǎn)單,服務(wù)器的端口號(hào)可以在“系統(tǒng)菜單”里面的參數(shù)配置進(jìn)行修改的。
看了上面的圖,下面我們就給大家把代碼貼出來(lái):(因?yàn)槌绦虮容^簡(jiǎn)單,所以本人就沒(méi)有去分層啦)
服務(wù)器端代碼:
- 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 配置參數(shù)ToolStripMenuItem_Click(object sender, EventArgs e)
- {
- Set TSet = new Set();
- TSet.ShowDialog();
- }
- private void 關(guān)于ToolStripMenuItem_Click(object sender, EventArgs e)
- {
- About TAbout = new About();
- TAbout.Show();
- }
- /// < summary>
- /// 獲得XML文件中的端口號(hào)
- /// < /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; }//默認(rèn)是6600
- }
- //聲明將要用到的類(lèi)
- private IPEndPoint ServerInfo;//存放服務(wù)器的IP和端口信息
- private Socket ServerSocket;//服務(wù)端運(yùn)行的SOCKET
- private Thread ServerThread;//服務(wù)端運(yùn)行的線程
- private Socket[] ClientSocket;//為客戶(hù)端建立的SOCKET連接
- private int ClientNumb;//存放客戶(hù)端數(shù)量
- private byte[] MsgBuffer;//存放消息數(shù)據(jù)
- 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);//開(kāi)始監(jiān)聽(tīng),并且掛起數(shù)為10
- ClientSocket = new Socket[65535];//為客戶(hù)端提供連接個(gè)數(shù)
- MsgBuffer = new byte[65535];//消息數(shù)據(jù)大小
- ClientNumb = 0;//數(shù)量從0開(kāi)始統(tǒng)計(jì)
- ServerThread = new Thread(RecieveAccept);//將接受客戶(hù)端連接的方法委托給線程
- ServerThread.Start();//線程開(kāi)始運(yùn)行
- CheckForIllegalCrossThreadCalls = false;//不捕獲對(duì)錯(cuò)誤線程的調(diào)用
- this.CmdStar.Enabled = false;
- this.CmdStop.Enabled = true;
- this.StateMsg.Text = "服務(wù)正在運(yùn)行"+" 運(yùn)行端口:"+this.GetPort().ToString();
- this.ClientList.Items.Add("服務(wù)于 " + DateTime.Now.ToString() + " 開(kāi)始運(yùn)行.");
- }
- //接受客戶(hù)端連接的方法
- 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()+" 成功連接服務(wù)器.");
- ClientNumb++;
- }
- }
- //回發(fā)數(shù)據(jù)給客戶(hù)端
- 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();//關(guān)閉SOCKET
- this.CmdStar.Enabled = true;
- this.CmdStop.Enabled = false;
- this.StateMsg.Text = "等待運(yùn)行";
- this.ClientList.Items.Add("服務(wù)于 " + DateTime.Now.ToString() + " 停止運(yùn)行.");
- }
- }
- }
客戶(hù)端代碼:
- 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 = "用戶(hù)" + 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("用戶(hù): " + this.UserName.Text + " 進(jìn)入系統(tǒng)!\n"));
- ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);
- this.SysMsg.Text += "登錄服務(wù)器成功!\n";
- this.CmdSend.Enabled = true;
- this.CmdEnter.Enabled = false;
- this.CmdExit.Enabled = true;
- }
- catch
- {
- MessageBox.Show("登錄服務(wù)器失敗,請(qǐng)確認(rèn)服務(wù)器是否正常工作!");
- }
- }
- 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("已經(jīng)與服務(wù)器斷開(kāi)連接!");
- this.Close();
- }
- }
- private void CmdSend_Click(object sender, EventArgs e)
- {
- MsgSend = Encoding.Unicode.GetBytes(this.UserName.Text + "說(shuō):\n" + this.SendMsg.Text + "\n");
- if (ClientSocket.Connected)
- {
- ClientSocket.Send(MsgSend);
- this.SendMsg.Text = "";
- }
- else
- {
- MessageBox.Show("當(dāng)前與服務(wù)器斷開(kāi)連接,無(wú)法發(fā)送信息!");
- }
- }
- private void CmdExit_Click(object sender, EventArgs e)
- {
- if (ClientSocket.Connected)
- {
- ClientSocket.Send(Encoding.Unicode.GetBytes(this.UserName.Text + "離開(kāi)了房間!\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);
- }
- }
- }
我只對(duì)服務(wù)器端的代碼做了注釋?zhuān)蛻?hù)端就沒(méi)有寫(xiě)注釋了,因?yàn)榇a是差不多的。區(qū)別在于客戶(hù)端不需要監(jiān)聽(tīng),也不需要啟用線程進(jìn)行委托。
關(guān)于 ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
這句代碼,我想給初學(xué)者解釋一下,這里“AddressFamily.InterNetwork”表示的是使用IPV4地址,“SocketType.Stream”表示使用的是流格式(另外還有數(shù)據(jù)包格式和原始套接字格式),“ProtocolType.Tcp”表示使用TCP協(xié)議(另外還有很多其它協(xié)議,例如大家常看到的UDP協(xié)議)。
服務(wù)器端+客戶(hù)端的聊天系統(tǒng)就介紹完了。另外關(guān)于SOCKET類(lèi)中的BeginReceive方法,請(qǐng)大家參考MSDN,里面有詳細(xì)說(shuō)明。
【編輯推薦】