自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

服務(wù)器+客戶(hù)端的聊天程序

開(kāi)發(fā) 后端
在當(dāng)今這樣一個(gè)網(wǎng)絡(luò)時(shí)代,很多技術(shù)都以網(wǎng)絡(luò)為中心在誕生。本文介紹了服務(wù)器端+客戶(hù)端的聊天系統(tǒng),希望對(duì)大家有用。

最近也在接觸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ù)端界面貼給大家看下:

客戶(hù)端界面 

功能比較簡(jiǎn)單,服務(wù)器的端口號(hào)可以在“系統(tǒng)菜單”里面的參數(shù)配置進(jìn)行修改的。

看了上面的圖,下面我們就給大家把代碼貼出來(lái):(因?yàn)槌绦虮容^簡(jiǎn)單,所以本人就沒(méi)有去分層啦)

服務(wù)器端代碼:

  1.  using System;  
  2.  using System.Collections.Generic;  
  3.  using System.ComponentModel;  
  4.  using System.Data;  
  5.  using System.Drawing;  
  6.  using System.Text;  
  7.  using System.Windows.Forms;  
  8.    
  9.  using System.Net;  
  10.  using System.Net.Sockets;  
  11.  using System.Threading;  
  12.  using System.Xml;  
  13.    
  14.  namespace Server  
  15.  {  
  16.      public partial class ServerMain : Form  
  17.      {  
  18.          public ServerMain()  
  19.          {  
  20.              InitializeComponent();  
  21.          }  
  22.    
  23.          private void ServerMain_Load(object sender, EventArgs e)  
  24.          {  
  25.              this.CmdStar.Enabled = true;  
  26.              this.CmdStop.Enabled = false;  
  27.          }  
  28.    
  29.          private void 配置參數(shù)ToolStripMenuItem_Click(object sender, EventArgs e)  
  30.          {  
  31.              Set TSet = new Set();  
  32.              TSet.ShowDialog();  
  33.          }  
  34.  
  35.          private void 關(guān)于ToolStripMenuItem_Click(object sender, EventArgs e)  
  36.          {  
  37.              About TAbout = new About();  
  38.              TAbout.Show();  
  39.          }  
  40.          /// < summary>  
  41.          /// 獲得XML文件中的端口號(hào)  
  42.          /// < /summary>  
  43.          /// < returns>< /returns>  
  44.          private int GetPort()  
  45.          {  
  46.              try 
  47.              {  
  48.                  XmlDocument TDoc = new XmlDocument();  
  49.                  TDoc.Load("Settings.xml");  
  50.                  string TPort = TDoc.GetElementsByTagName("ServerPort")[0].InnerXml;  
  51.                  return Convert.ToInt32(TPort);  
  52.    
  53.              }  
  54.              catch { return 6600; }//默認(rèn)是6600  
  55.          }  
  56.    
  57.          //聲明將要用到的類(lèi)  
  58.          private IPEndPoint ServerInfo;//存放服務(wù)器的IP和端口信息  
  59.          private Socket ServerSocket;//服務(wù)端運(yùn)行的SOCKET  
  60.          private Thread ServerThread;//服務(wù)端運(yùn)行的線程  
  61.          private Socket[] ClientSocket;//為客戶(hù)端建立的SOCKET連接  
  62.          private int ClientNumb;//存放客戶(hù)端數(shù)量  
  63.          private byte[] MsgBuffer;//存放消息數(shù)據(jù)  
  64.    
  65.          private void CmdStar_Click(object sender, EventArgs e)  
  66.          {  
  67.              ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  68.              ServerInfo=new IPEndPoint(IPAddress.Any,this.GetPort());  
  69.              ServerSocket.Bind(ServerInfo);//將SOCKET接口和IP端口綁定  
  70.              ServerSocket.Listen(10);//開(kāi)始監(jiān)聽(tīng),并且掛起數(shù)為10  
  71.    
  72.              ClientSocket = new Socket[65535];//為客戶(hù)端提供連接個(gè)數(shù)  
  73.              MsgBuffer = new byte[65535];//消息數(shù)據(jù)大小  
  74.              ClientNumb = 0;//數(shù)量從0開(kāi)始統(tǒng)計(jì)  
  75.    
  76.              ServerThread = new Thread(RecieveAccept);//將接受客戶(hù)端連接的方法委托給線程  
  77.              ServerThread.Start();//線程開(kāi)始運(yùn)行  
  78.    
  79.              CheckForIllegalCrossThreadCalls = false;//不捕獲對(duì)錯(cuò)誤線程的調(diào)用  
  80.    
  81.              this.CmdStar.Enabled = false;  
  82.              this.CmdStop.Enabled = true;  
  83.              this.StateMsg.Text = "服務(wù)正在運(yùn)行"+"  運(yùn)行端口:"+this.GetPort().ToString();  
  84.              this.ClientList.Items.Add("服務(wù)于 " + DateTime.Now.ToString() + " 開(kāi)始運(yùn)行.");  
  85.          }  
  86.            
  87.          //接受客戶(hù)端連接的方法  
  88.          private void RecieveAccept()  
  89.          {  
  90.              while (true)  
  91.              {  
  92.                  ClientSocket[ClientNumb] = ServerSocket.Accept();  
  93.                  ClientSocket[ClientNumb].BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack),ClientSocket[ClientNumb]);  
  94.                  this.ClientList.Items.Add(ClientSocket[ClientNumb].RemoteEndPoint.ToString()+" 成功連接服務(wù)器.");  
  95.                  ClientNumb++;  
  96.              }  
  97.          }  
  98.    
  99.          //回發(fā)數(shù)據(jù)給客戶(hù)端  
  100.         private void RecieveCallBack(IAsyncResult AR)  
  101.         {  
  102.             try 
  103.             {  
  104.                 Socket RSocket = (Socket)AR.AsyncState;  
  105.                 int REnd = RSocket.EndReceive(AR);  
  106.                 for (int i = 0; i <  ClientNumb; i++)  
  107.                 {  
  108.                     if (ClientSocket[i].Connected)  
  109.                     {  
  110.                         ClientSocket[i].Send(MsgBuffer, 0, REnd,0);  
  111.                     }  
  112.                     RSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(RecieveCallBack), RSocket);  
  113.  
  114.                 }  
  115.             }  
  116.             catch { }  
  117.  
  118.         }  
  119.  
  120.         private void CmdStop_Click(object sender, EventArgs e)  
  121.         {  
  122.             ServerThread.Abort();//線程終止  
  123.             ServerSocket.Close();//關(guān)閉SOCKET  
  124.  
  125.             this.CmdStar.Enabled = true;  
  126.             this.CmdStop.Enabled = false;  
  127.             this.StateMsg.Text = "等待運(yùn)行";  
  128.             this.ClientList.Items.Add("服務(wù)于 " + DateTime.Now.ToString() + " 停止運(yùn)行.");  
  129.         }  
  130.  
  131.  
  132.  
  133.     }  

客戶(hù)端代碼:

  1.  using System;  
  2.  using System.Collections.Generic;  
  3.  using System.ComponentModel;  
  4.  using System.Data;  
  5.  using System.Drawing;  
  6.  using System.Text;  
  7.  using System.Windows.Forms;  
  8.    
  9.  using System.Net;  
  10.  using System.Net.Sockets;  
  11.  
  12. namespace Client  
  13. {  
  14.     public partial class ClientMain : Form  
  15.     {  
  16.         public ClientMain()  
  17.         {  
  18.             InitializeComponent();  
  19.         }  
  20.  
  21.         private IPEndPoint ServerInfo;  
  22.         private Socket ClientSocket;  
  23.         private Byte[] MsgBuffer;  
  24.         private Byte[] MsgSend;  
  25.  
  26.         private void ClientMain_Load(object sender, EventArgs e)  
  27.         {  
  28.             this.CmdSend.Enabled = false;  
  29.             this.CmdExit.Enabled = false;  
  30.  
  31.             ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  
  32.             MsgBuffer = new Byte[65535];  
  33.             MsgSend = new Byte[65535];  
  34.             CheckForIllegalCrossThreadCalls = false;  
  35.  
  36.             Random TRand=new Random();  
  37.             this.UserName.Text = "用戶(hù)" + TRand.Next(10000).ToString();  
  38.         }  
  39.  
  40.         private void CmdEnter_Click(object sender, EventArgs e)  
  41.         {  
  42.             ServerInfo = new IPEndPoint(IPAddress.Parse(this.ServerIP.Text), Convert.ToInt32(this.ServerPort.Text));  
  43.  
  44.             try 
  45.             {  
  46.                 ClientSocket.Connect(ServerInfo);  
  47.  
  48.                 ClientSocket.Send(Encoding.Unicode.GetBytes("用戶(hù): " + this.UserName.Text + " 進(jìn)入系統(tǒng)!\n"));  
  49.  
  50.                 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);  
  51.  
  52.                 this.SysMsg.Text += "登錄服務(wù)器成功!\n";  
  53.                 this.CmdSend.Enabled = true;  
  54.                 this.CmdEnter.Enabled = false;  
  55.                 this.CmdExit.Enabled = true;  
  56.             }  
  57.             catch 
  58.             {  
  59.                 MessageBox.Show("登錄服務(wù)器失敗,請(qǐng)確認(rèn)服務(wù)器是否正常工作!");  
  60.             }  
  61.         }  
  62.  
  63.         private void ReceiveCallBack(IAsyncResult AR)  
  64.         {  
  65.             try 
  66.             {  
  67.                 int REnd = ClientSocket.EndReceive(AR);  
  68.                 this.RecieveMsg.AppendText(Encoding.Unicode.GetString(MsgBuffer, 0, REnd));  
  69.                 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallBack), null);  
  70.  
  71.             }  
  72.             catch 
  73.             {  
  74.                 MessageBox.Show("已經(jīng)與服務(wù)器斷開(kāi)連接!");  
  75.                 this.Close();  
  76.            }  
  77.  
  78.         }  
  79.  
  80.         private void CmdSend_Click(object sender, EventArgs e)  
  81.         {  
  82.            MsgSend = Encoding.Unicode.GetBytes(this.UserName.Text + "說(shuō):\n" + this.SendMsg.Text + "\n");  
  83.             if (ClientSocket.Connected)  
  84.             {  
  85.                 ClientSocket.Send(MsgSend);  
  86.                 this.SendMsg.Text = "";  
  87.             }  
  88.             else 
  89.             {  
  90.                 MessageBox.Show("當(dāng)前與服務(wù)器斷開(kāi)連接,無(wú)法發(fā)送信息!");  
  91.             }  
  92.         }  
  93.  
  94.         private void CmdExit_Click(object sender, EventArgs e)  
  95.         {  
  96.             if (ClientSocket.Connected)  
  97.             {  
  98.                 ClientSocket.Send(Encoding.Unicode.GetBytes(this.UserName.Text + "離開(kāi)了房間!\n"));  
  99.                 ClientSocket.Shutdown(SocketShutdown.Both);  
  100.                ClientSocket.Disconnect(false);  
  101.            }  
  102.            ClientSocket.Close();  
  103.  
  104.            this.CmdSend.Enabled = false;  
  105.            this.CmdEnter.Enabled = true;  
  106.            this.CmdExit.Enabled = false;  
  107.        }  
  108.  
  109.        private void RecieveMsg_TextChanged(object sender, EventArgs e)  
  110.        {  
  111.            this.RecieveMsg.ScrollToCaret();  
  112.        }  
  113.  
  114.        private void SendMsg_KeyDown(object sender, KeyEventArgs e)  
  115.        {  
  116.            if (e.Control && e.KeyValue == 13)  
  117.            {  
  118.                e.Handled = true;  
  119.                this.CmdSend_Click(thisnull);  
  120.            }  
  121.        }  
  122.  
  123.  
  124.  
  125.  
  126.    }  

我只對(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ō)明。

【編輯推薦】

  1. 關(guān)于C#知識(shí)點(diǎn)總結(jié)
  2. C#開(kāi)發(fā)和使用中的33個(gè)技巧
  3. SQL Server存儲(chǔ)過(guò)程介紹
  4. C#下SQL Server 2008表類(lèi)型參數(shù)傳遞
  5. C#向SQL Server中插入記錄時(shí)的問(wèn)題
責(zé)任編輯:book05 來(lái)源: 博客園
相關(guān)推薦

2011-06-09 10:51:26

Qt 服務(wù)器 客戶(hù)端

2014-01-17 15:23:55

Nagios

2010-06-09 14:39:58

2018-12-18 10:47:37

2018-07-17 09:59:10

PythonUDP服務(wù)器

2009-12-25 10:47:17

DNS服務(wù)器

2019-08-28 15:19:15

PythonTCP服務(wù)器

2009-09-16 16:09:41

NIS服務(wù)器客戶(hù)端NIS

2018-12-19 10:31:32

客戶(hù)端IP服務(wù)器

2012-05-29 09:38:04

Linux客戶(hù)端服務(wù)器

2018-12-20 08:50:53

TCPIP服務(wù)器

2010-10-11 17:46:01

mysql客戶(hù)端

2010-10-26 13:54:45

連接Oracle服務(wù)器

2010-08-27 10:18:24

DHCP服務(wù)

2009-06-27 20:32:00

LinuxNFS客戶(hù)端

2014-06-01 11:03:13

VDI零客戶(hù)端

2024-02-22 13:47:40

2012-05-07 13:55:41

JavaJava Web

2009-06-10 16:25:02

2010-09-03 12:12:27

DHCP服務(wù)器客戶(hù)端
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)