c#仿照相似qq的通訊聊天程序


即時通訊系統開發 編程

在咱們的生活中常用即時通訊的軟件,咱們常常接觸到的有:QQ、阿里旺旺、MSN等等。這些都是屬於即時通訊(Instant Messenger,IM)軟件,IM是指全部可以即時發送和接收互聯網消息的軟件。 服務器

在前面專題P2P編程中介紹過P2P系統分兩種類型——單純型P2P和混合型P2P(QQ就是屬於混合型的應用),混合型P2P系統中的服務器(也叫索引服務器)起到協調的做用。在文件共享類應用中,若是採用混合型P2P技術的話,索引服務器就保存着文件信息,這樣就可能會形成版權的問題,然而在即時通訊類的軟件中, 由於客戶端傳遞的都是簡單的聊天文本而不是網絡媒體資源,這樣就不存在版權問題了,在這種狀況下,就能夠採用混合型P2P技術來實現咱們的即時通訊軟件。前面已經講了,騰訊的QQ就是屬於混合型P2P的軟件。 網絡

所以本專題要實現一個相似QQ的聊天程序,其中用到的P2P技術是屬於混合型P2P,而不是前一專題中的採用的單純型P2P技術,同時本程序的實現也會用到TCP、UDP編程技術。具體的相關內容你們能夠查看本系列的相關專題的。 dom

2、程序實現的詳細設計 tcp

本程序採用P2P方式,各個客戶端之間直接發消息進行聊天,服務器在其中只是起到協調的做用,下面先理清下程序的流程: this

2.1 程序流程設計 spa

當一個新用戶經過客戶端登錄系統後,從服務器獲取當在線的用戶信息列表,列表信息包括系統中每一個用戶的地址,而後用戶就能夠單獨向其餘發消息。若是有用戶加入或者在線用戶退出時,服務器就會及時發消息通知系統中的全部其餘客戶端,達到它們即時地更新用戶信息列表。 插件

根據上面大體的描述,咱們能夠把系統的流程分爲下面幾步來更好的理解(你們能夠參考QQ程序將會更好的理解本程序的流程): 線程

1.用戶經過客戶端進入系統,向服務器發出消息,請求登錄 設計

2.服務器收到請求後,向客戶端返回迴應消息,表示贊成接受該用戶加入,並把本身(指的是服務器)所在監聽的端口發送給客戶端

3.客戶端根據服務器發送過來的端口號和服務器創建鏈接

4.服務器經過該鏈接 把在線用戶的列表信息發送給新加入的客戶端。

5.客戶端得到了在線用戶列表後就能夠本身選擇在線用戶聊天。(程序中另外設計一個相似QQ的聊天窗口來進行聊天)

6.當用戶退出系統時也要及時通知服務器,服務器再把這個消息轉發給每一個在線的用戶,使客戶端及時更新本地的用戶信息列表。

2.2 通訊協議設計

所謂協議就是約定,即服務器和客戶端之間會話信息的內容格式進行約定,使雙方均可以識別,達到更好的通訊。

下面就具體介紹下協議的設計:

1. 客戶端和服務器之間的對話

(1)登錄過程

① 客戶端用匿名UDP的方式向服務器發出下面的信息:

   login, username, localIPEndPoint

消息內容包括三個字段,每一個字段用 「,」分割,login表示的是請求登錄;username表示用戶名;localIPEndPint表示客戶端本地地址。

② 服務器收到後以匿名UDP返回下面的迴應:

Accept, port

其中Accept表示服務器接受請求,port表示服務器所在的端口號,服務器監聽着這個端口的客戶端鏈接

③ 鏈接服務器,獲取用戶列表

客戶端從上一步得到了端口號,而後向該端口發起TCP鏈接,向服務器索取在線用戶列表,服務器接受鏈接後將用戶列表傳輸到客戶端。用戶列表信息格式以下:

  username1,IPEndPoint1;username2,IPEndPoint2;...;end

username一、username2表示用戶名,IPEndPoint1,IPEndPoint2表示對應的端點,每一個用戶信息都是由"用戶名+端點"組成,用戶信息以「;」隔開,整個用戶列表以「end」結尾。

(2)註銷過程

用戶退出時,向服務器發送以下消息:

   logout,username,localIPEndPoint

這條消息看字面意思你們都知道就是告訴服務器 username+localIPEndPoint這個用戶要退出了。

2. 服務器管理用戶

(1)新用戶加入通知

由於系統中在線的每一個用戶都有一份當前在線用戶表,所以當有新用戶登陸時,服務器不須要重複地給系統中的每一個用戶再發送全部用戶信息,只須要將新加入用戶的信息通知其餘用戶,其餘用戶再更新本身的用戶列表。

服務器向系統中每一個用戶廣播以下信息:

login,username,remoteIPEndPoint

在這個過程當中服務器只是負責將收到的"login"信息轉發出去。

(2)用戶退出

與新用戶加入同樣,服務器將用戶退出的消息進行廣播轉發:

    logout,username,remoteIPEndPoint

3. 客戶端之間聊天

用戶進行聊天時,各自的客戶端之間是以P2P方式進行工做的,不與服務器有直接聯繫,這也是P2P技術的特色。

聊天發送的消息格式以下:

 talk, longtime, selfUserName, message

其中,talk代表這是聊天內容的消息;longtime是長時間格式的當前系統時間;selfUserName爲發送發的用戶名;message表示消息的內容。

協議設計介紹完後,下面就進入本程序的具體實現的介紹的。

注:協議是本程序的核心,也是全部軟件的核心,每一個軟件產品的協議都是不同的,QQ有本身的一套協議,MSN又有另外一套協議,因此使用的QQ的用戶沒法和用MSN的朋友進行聊天。

首先運行visual 2010,net平臺開發。


程序實現

 
  1. View Code   
  2.   // 啓動服務器  
  3.          // 根據博客中協議的設計部分  
  4.          // 客戶端先向服務器發送登陸請求,而後經過服務器返回的端口號  
  5.          // 再與服務器創建鏈接  
  6.          // 因此啓動服務按鈕事件中有兩個套接字:一個是接收客戶端信息套接字和  
  7.          // 監聽客戶端鏈接套接字  
  8.          private void btnStart_Click(object sender, EventArgs e)  
  9.          {  
  10.              // 建立接收套接字  
  11.              serverIp = IPAddress.Parse(txbServerIP.Text);  
  12.              serverIPEndPoint = new IPEndPoint(serverIp, int.Parse(txbServerport.Text));  
  13.              receiveUdpClient = new UdpClient(serverIPEndPoint);  
  14.              // 啓動接收線程  
  15.              Thread receiveThread = new Thread(ReceiveMessage);  
  16.              receiveThread.Start();  
  17.              btnStart.Enabled = false;  
  18.              btnStop.Enabled = true;  
  19.    
  20.              // 隨機指定監聽端口  
  21.              Random random = new Random();  
  22.              tcpPort = random.Next(port + 1, 65536);  
  23.    
  24.              // 建立監聽套接字  
  25.              tcpListener = new TcpListener(serverIp, tcpPort);  
  26.              tcpListener.Start();  
  27.    
  28.              // 啓動監聽線程  
  29.              Thread listenThread = new Thread(ListenClientConnect);  
  30.              listenThread.Start();  
  31.              AddItemToListBox(string.Format("服務器線程{0}啓動,監聽端口{1}",serverIPEndPoint,tcpPort));  
  32.          }  
  33.    
  34.          // 接收客戶端發來的信息  
  35.          private void ReceiveMessage()  
  36.          {  
  37.              IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);  
  38.              while (true)  
  39.              {  
  40.                  try 
  41.                  {  
  42.                      // 關閉receiveUdpClient時下面一行代碼會產生異常  
  43.                      byte[] receiveBytes = receiveUdpClient.Receive(ref remoteIPEndPoint);  
  44.                      string message = Encoding.Unicode.GetString(receiveBytes, 0, receiveBytes.Length);  
  45.    
  46.                      // 顯示消息內容  
  47.                      AddItemToListBox(string.Format("{0}:{1}",remoteIPEndPoint,message));  
  48.    
  49.                      // 處理消息數據  
  50.                      // 根據協議的設計部分,從客戶端發送來的消息是具備必定格式的  
  51.                      // 服務器接收消息後要對消息作處理  
  52.                      string[] splitstring = message.Split(',');  
  53.                      // 解析用戶端地址  
  54.                      string[] splitsubstring = splitstring[2].Split(':');  
  55.                      IPEndPoint clientIPEndPoint = new IPEndPoint(IPAddress.Parse(splitsubstring[0]), int.Parse(splitsubstring[1]));  
  56.                      switch (splitstring[0])  
  57.                      {  
  58.                          // 若是是登陸信息,向客戶端發送應答消息和廣播有新用戶登陸消息  
  59.                          case "login":  
  60.                              User user = new User(splitstring[1], clientIPEndPoint);  
  61.                              // 往在線的用戶列表添加新成員  
  62.                              userList.Add(user);  
  63.                              AddItemToListBox(string.Format("用戶{0}({1})加入", user.GetName(), user.GetIPEndPoint()));  
  64.                              string sendString = "Accept," + tcpPort.ToString();  
  65.                              // 向客戶端發送應答消息  
  66.                              SendtoClient(user, sendString);  
  67.                              AddItemToListBox(string.Format("向{0}({1})發出:[{2}]", user.GetName(), user.GetIPEndPoint(), sendString));  
  68.                              for (int i = 0; i < userList.Count; i++)  
  69.                              {  
  70.                                  if (userList[i].GetName() != user.GetName())  
  71.                                  {  
  72.                                      // 給在線的其餘用戶發送廣播消息  
  73.                                      // 通知有新用戶加入  
  74.                                      SendtoClient(userList[i], message);  
  75.                                  }  
  76.                              }  
  77.    
  78.                              AddItemToListBox(string.Format("廣播:[{0}]", message));  
  79.                              break;  
  80.                          case "logout":  
  81.                              for (int i = 0; i < userList.Count; i++)  
  82.                              {  
  83.                                  if (userList[i].GetName() == splitstring[1])  
  84.                                  {  
  85.                                      AddItemToListBox(string.Format("用戶{0}({1})退出",userList[i].GetName(),userList[i].GetIPEndPoint()));  
  86.                                      userList.RemoveAt(i); // 移除用戶  
  87.                                  }  
  88.                              }  
  89.                              for (int i = 0; i < userList.Count; i++)  
  90.                              {  
  91.                                  // 廣播註銷消息  
  92.                                  SendtoClient(userList[i], message);  
  93.                              }  
  94.                              AddItemToListBox(string.Format("廣播:[{0}]", message));  
  95.                              break;  
  96.                      }  
  97.                  }  
  98.                  catch 
  99.                  {  
  100.                      // 發送異常退出循環  
  101.                      break;  
  102.                  }  
  103.              }  
  104.              AddItemToListBox(string.Format("服務線程{0}終止", serverIPEndPoint));  
  105.          }  
  106.    
  107.          // 向客戶端發送消息  
  108.          private void SendtoClient(User user, string message)  
  109.          {  
  110.              // 匿名方式發送  
  111.              sendUdpClient = new UdpClient(0);  
  112.              byte[] sendBytes = Encoding.Unicode.GetBytes(message);  
  113.              IPEndPoint remoteIPEndPoint =user.GetIPEndPoint();  
  114.              sendUdpClient.Send(sendBytes,sendBytes.Length,remoteIPEndPoint);  
  115.              sendUdpClient.Close();  
  116.          }  
  117.           
  118.          // 接受客戶端的鏈接  
  119.          private void ListenClientConnect()  
  120.          {  
  121.              TcpClient newClient = null;  
  122.              while (true)  
  123.              {  
  124.                  try 
  125.                  {  
  126.                      newClient = tcpListener.AcceptTcpClient();  
  127.                      AddItemToListBox(string.Format("接受客戶端{0}的TCP請求",newClient.Client.RemoteEndPoint));  
  128.                  }  
  129.                  catch 
  130.                  {  
  131.                      AddItemToListBox(string.Format("監聽線程({0}:{1})", serverIp, tcpPort));  
  132.                      break;  
  133.                  }  
  134.    
  135.                  Thread sendThread = new Thread(SendData);  
  136.                  sendThread.Start(newClient);  
  137.              }  
  138.          }  
  139.    
  140.          // 向客戶端發送在線用戶列表信息  
  141.          // 服務器經過TCP鏈接把在線用戶列表信息發送給客戶端  
  142.          private void SendData(object userClient)  
  143.          {  
  144.              TcpClient newUserClient = (TcpClient)userClient;  
  145.              userListstring = null;  
  146.              for (int i = 0; i < userList.Count; i++)  
  147.              {  
  148.                  userListstring += userList[i].GetName() + "," 
  149.                      + userList[i].GetIPEndPoint().ToString() + ";";  
  150.              }  
  151.    
  152.              userListstring += "end";  
  153.              networkStream = newUserClient.GetStream();  
  154.              binaryWriter = new BinaryWriter(networkStream);  
  155.              binaryWriter.Write(userListstring);  
  156.              binaryWriter.Flush();  
  157.              AddItemToListBox(string.Format("向{0}發送[{1}]", newUserClient.Client.RemoteEndPoint, userListstring));  
  158.              binaryWriter.Close();  
  159.              newUserClient.Close();  
  160.          } 

客戶端核心代碼:

 
  1. View Code   
  2.   // 登陸服務器  
  3.          private void btnlogin_Click(object sender, EventArgs e)  
  4.          {  
  5.              // 建立接受套接字  
  6.              IPAddress clientIP = IPAddress.Parse(txtLocalIP.Text);  
  7.              clientIPEndPoint = new IPEndPoint(clientIP, int.Parse(txtlocalport.Text));  
  8.              receiveUdpClient = new UdpClient(clientIPEndPoint);  
  9.              // 啓動接收線程  
  10.              Thread receiveThread = new Thread(ReceiveMessage);  
  11.              receiveThread.Start();  
  12.    
  13.              // 匿名發送  
  14.              sendUdpClient = new UdpClient(0);  
  15.              // 啓動發送線程  
  16.              Thread sendThread = new Thread(SendMessage);  
  17.              sendThread.Start(string.Format("login,{0},{1}", txtusername.Text, clientIPEndPoint));  
  18.    
  19.              btnlogin.Enabled = false;  
  20.              btnLogout.Enabled = true;  
  21.              this.Text = txtusername.Text;  
  22.          }  
  23.    
  24.          // 客戶端接受服務器迴應消息   
  25.          private void ReceiveMessage()  
  26.          {  
  27.              IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any,0);  
  28.              while (true)  
  29.              {  
  30.                  try 
  31.                  {  
  32.                      // 關閉receiveUdpClient時會產生異常  
  33.                      byte[] receiveBytes = receiveUdpClient.Receive(ref remoteIPEndPoint);  
  34.                      string message = Encoding.Unicode.GetString(receiveBytes,0,receiveBytes.Length);  
  35.    
  36.                      // 處理消息  
  37.                      string[] splitstring = message.Split(',');  
  38.    
  39.                      switch (splitstring[0])  
  40.                      {  
  41.                          case "Accept":  
  42.                              try 
  43.                              {  
  44.                                  tcpClient = new TcpClient();  
  45.                                  tcpClient.Connect(remoteIPEndPoint.Address, int.Parse(splitstring[1]));  
  46.                                  if (tcpClient != null)  
  47.                                  {  
  48.                                      // 表示鏈接成功  
  49.                                      networkStream = tcpClient.GetStream();  
  50.                                      binaryReader = new BinaryReader(networkStream);  
  51.                                  }  
  52.                              }  
  53.                              catch 
  54.                              {  
  55.                                  MessageBox.Show("鏈接失敗""異常");  
  56.                              }  
  57.    
  58.                              Thread getUserListThread = new Thread(GetUserList);  
  59.                              getUserListThread.Start();  
  60.                              break;  
  61.                          case "login":  
  62.                              string userItem = splitstring[1] + "," + splitstring[2];  
  63.                              AddItemToListView(userItem);  
  64.                              break;  
  65.                          case "logout":  
  66.                              RemoveItemFromListView(splitstring[1]);  
  67.                              break;  
  68.                          case "talk":  
  69.                              for (int i = 0; i < chatFormList.Count; i++)  
  70.                              {  
  71.                                  if (chatFormList[i].Text == splitstring[2])  
  72.                                  {  
  73.                                      chatFormList[i].ShowTalkInfo(splitstring[2], splitstring[1], splitstring[3]);  
  74.                                  }  
  75.                              }  
  76.    
  77.                              break;  
  78.                      }  
  79.                  }  
  80.                  catch 
  81.                  {  
  82.                      break;  
  83.                  }  
  84.              }  
  85.          }  
  86.    
  87.          // 從服務器獲取在線用戶列表  
  88.          private void GetUserList()  
  89.          {  
  90.              while (true)  
  91.              {  
  92.                  userListstring = null;  
  93.                  try 
  94.                  {  
  95.                      userListstring = binaryReader.ReadString();  
  96.                      if (userListstring.EndsWith("end"))  
  97.                      {  
  98.                          string[] splitstring = userListstring.Split(';');  
  99.                          for (int i = 0; i < splitstring.Length - 1; i++)  
  100.                          {  
  101.                              AddItemToListView(splitstring[i]);  
  102.                          }  
  103.    
  104.                          binaryReader.Close();  
  105.                          tcpClient.Close();  
  106.                          break;  
  107.                      }  
  108.                  }  
  109.                  catch 
  110.                  {  
  111.                      break;  
  112.                  }  
  113.              }  
  114.          }  
  115.     // 發送登陸請求  
  116.          private void SendMessage(object obj)  
  117.          {  
  118.              string message = (string)obj;  
  119.              byte[] sendbytes = Encoding.Unicode.GetBytes(message);  
  120.              IPAddress remoteIp = IPAddress.Parse(txtserverIP.Text);  
  121.              IPEndPoint remoteIPEndPoint = new IPEndPoint(remoteIp, int.Parse(txtServerport.Text));  
  122.              sendUdpClient.Send(sendbytes, sendbytes.Length, remoteIPEndPoint);  
  123.              sendUdpClient.Close();  
  124.          } 

程序的運行結果:

首先先運行服務器窗口,在服務器窗口點擊「啓動」按鈕來啓動服務器,而後客戶端首先指定服務器的端口號,修改用戶名(這裏也能夠不修改,使用默認的也能夠),而後點擊「登陸」按鈕來登錄服務器(也就是告訴服務器本地的客戶端地址),而後從服務器端得到在線用戶列表,界面演示以下:

而後用戶能夠雙擊在線用戶進行聊天(此程序支持與多人進行聊天),下面是功能的演示圖片:

雙方進行聊天時,這裏沒有實現像QQ同樣,有人發信息來在對應的客戶端就有消息提醒的功能的, 因此雙方進行聊天的過程當中,每一個客戶端都須要在在線用戶列表中點擊聊天的對象來激活聊天對話框(意思就是從圖片中能夠看出「天涯」客戶端想和劍癡聊天的話,就在「在線用戶」列表雙擊劍癡來激活聊天窗口,同時「劍癡」客戶端也必須雙擊「天涯」來激活聊天窗口,這樣雙方就看到對方發來的信息了,(不激活窗口,也是發送了信息,只是沒有一個窗口來進行顯示)),並且從圖片中也能夠看出——此程序支持與多人聊天,即天涯同時與「劍癡」和"大地"同時聊天。

在此基礎上,能夠實現程序更多的功能,要靠插件完成

end

相關文章
相關標籤/搜索