溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#的即時通信程序怎么實現(xiàn)

發(fā)布時間:2021-12-03 10:28:46 來源:億速云 閱讀:173 作者:iii 欄目:編程語言

這篇文章主要介紹“C#的即時通信程序怎么實現(xiàn)”,在日常操作中,相信很多人在C#的即時通信程序怎么實現(xiàn)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C#的即時通信程序怎么實現(xiàn)”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

一、即時通信系統(tǒng)

在我們的生活中經常使用即時通信的軟件,我們經常接觸到的有:QQ、阿里旺旺、MSN等等。這些都是屬于即時通信(Instant Messenger,IM)軟件,IM是指所有能夠即時發(fā)送和接收互聯(lián)網消息的軟件。

在前面專題P2P編程中介紹過P2P系統(tǒng)分兩種類型——單純型P2P和混合型P2P(QQ就是屬于混合型的應用),混合型P2P系統(tǒng)中的服務器(也叫索引服務器)起到協(xié)調的作用。在文件共享類應用中,如果采用混合型P2P技術的話,索引服務器就保存著文件信息,這樣就可能會造成版權的問題,然而在即時通信類的軟件中, 因為客戶端傳遞的都是簡單的聊天文本而不是網絡媒體資源,這樣就不存在版權問題了,在這種情況下,就可以采用混合型P2P技術來實現(xiàn)我們的即時通信軟件。前面已經講了,騰訊的QQ就是屬于混合型P2P的軟件。

因此本專題要實現(xiàn)一個類似QQ的聊天程序,其中用到的P2P技術是屬于混合型P2P,而不是前一專題中的采用的單純型P2P技術,同時本程序的實現(xiàn)也會用到TCP、UDP編程技術。具體的相關內容大家可以查看本系列的相關專題的。

二、程序實現(xiàn)的詳細設計

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

2.1 程序流程設計

當一個新用戶通過客戶端登陸系統(tǒng)后,從服務器獲取當在線的用戶信息列表,列表信息包括系統(tǒng)中每個用戶的地址,然后用戶就可以單獨向其他發(fā)消息。如果有用戶加入或者在線用戶退出時,服務器就會及時發(fā)消息通知系統(tǒng)中的所有其他客戶端,達到它們即時地更新用戶信息列表。

根據(jù)上面大致的描述,我們可以把系統(tǒng)的流程分為下面幾步來更好的理解(大家可以參考QQ程序將會更好的理解本程序的流程):

1.用戶通過客戶端進入系統(tǒng),向服務器發(fā)出消息,請求登陸

2.服務器收到請求后,向客戶端返回回應消息,表示同意接受該用戶加入,并把自己(指的是服務器)所在監(jiān)聽的端口發(fā)送給客戶端

3.客戶端根據(jù)服務器發(fā)送過來的端口號和服務器建立連接

4.服務器通過該連接 把在線用戶的列表信息發(fā)送給新加入的客戶端。

5.客戶端獲得了在線用戶列表后就可以自己選擇在線用戶聊天。(程序中另外設計一個類似QQ的聊天窗口來進行聊天)

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

2.2 通信協(xié)議設計

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

下面就具體介紹下協(xié)議的設計:

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

(1)登陸過程

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

   login, username, localIPEndPoint

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

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

Accept, port

其中Accept表示服務器接受請求,port表示服務器所在的端口號,服務器監(jiān)聽著這個端口的客戶端連接

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

客戶端從上一步獲得了端口號,然后向該端口發(fā)起TCP連接,向服務器索取在線用戶列表,服務器接受連接后將用戶列表傳輸?shù)娇蛻舳?。用戶列表信息格式如下?/p>

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

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

(2)注銷過程

用戶退出時,向服務器發(fā)送如下消息:

   logout,username,localIPEndPoint

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

2. 服務器管理用戶

(1)新用戶加入通知

因為系統(tǒng)中在線的每個用戶都有一份當前在線用戶表,因此當有新用戶登錄時,服務器不需要重復地給系統(tǒng)中的每個用戶再發(fā)送所有用戶信息,只需要將新加入用戶的信息通知其他用戶,其他用戶再更新自己的用戶列表。

服務器向系統(tǒng)中每個用戶廣播如下信息:

login,username,remoteIPEndPoint

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

(2)用戶退出

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

    logout,username,remoteIPEndPoint

3. 客戶端之間聊天

用戶進行聊天時,各自的客戶端之間是以P2P方式進行工作的,不與服務器有直接聯(lián)系,這也是P2P技術的特點。

聊天發(fā)送的消息格式如下:

 talk, longtime, selfUserName, message

其中,talk表明這是聊天內容的消息;longtime是長時間格式的當前系統(tǒng)時間;selfUserName為發(fā)送發(fā)的用戶名;message表示消息的內容。

協(xié)議設計介紹完后,下面就進入本程序的具體實現(xiàn)的介紹的。

注:協(xié)議是本程序的核心,也是所有軟件的核心,每個軟件產品的協(xié)議都是不一樣的,QQ有自己的一套協(xié)議,MSN又有另一套協(xié)議,所以使用的QQ的用戶無法和用MSN的朋友進行聊天。

三、程序的實現(xiàn)

服務器端核心代碼:

View Code     // 啟動服務器           // 根據(jù)博客中協(xié)議的設計部分           // 客戶端先向服務器發(fā)送登錄請求,然后通過服務器返回的端口號           // 再與服務器建立連接           // 所以啟動服務按鈕事件中有兩個套接字:一個是接收客戶端信息套接字和           // 監(jiān)聽客戶端連接套接字           private void btnStart_Click(object sender, EventArgs e)           {               // 創(chuàng)建接收套接字               serverIp = IPAddress.Parse(txbServerIP.Text);               serverIPEndPoint = new IPEndPoint(serverIp, int.Parse(txbServerport.Text));               receiveUdpClient = new UdpClient(serverIPEndPoint);               // 啟動接收線程               Thread receiveThread = new Thread(ReceiveMessage);               receiveThread.Start();               btnStart.Enabled = false;               btnStop.Enabled = true;                  // 隨機指定監(jiān)聽端口               Random random = new Random();               tcpPort = random.Next(port + 1, 65536);                  // 創(chuàng)建監(jiān)聽套接字               tcpListener = new TcpListener(serverIp, tcpPort);               tcpListener.Start();                  // 啟動監(jiān)聽線程               Thread listenThread = new Thread(ListenClientConnect);               listenThread.Start();               AddItemToListBox(string.Format("服務器線程{0}啟動,監(jiān)聽端口{1}",serverIPEndPoint,tcpPort));           }              // 接收客戶端發(fā)來的信息           private void ReceiveMessage()           {               IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);               while (true)               {                   try                  {                       // 關閉receiveUdpClient時下面一行代碼會產生異常                       byte[] receiveBytes = receiveUdpClient.Receive(ref remoteIPEndPoint);                       string message = Encoding.Unicode.GetString(receiveBytes, 0, receiveBytes.Length);                          // 顯示消息內容                       AddItemToListBox(string.Format("{0}:{1}",remoteIPEndPoint,message));                          // 處理消息數(shù)據(jù)                       // 根據(jù)協(xié)議的設計部分,從客戶端發(fā)送來的消息是具有一定格式的                       // 服務器接收消息后要對消息做處理                       string[] splitstring = message.Split(',');                       // 解析用戶端地址                       string[] splitsubstring = splitstring[2].Split(':');                       IPEndPoint clientIPEndPoint = new IPEndPoint(IPAddress.Parse(splitsubstring[0]), int.Parse(splitsubstring[1]));                       switch (splitstring[0])                       {                           // 如果是登錄信息,向客戶端發(fā)送應答消息和廣播有新用戶登錄消息                           case "login":                               User user = new User(splitstring[1], clientIPEndPoint);                               // 往在線的用戶列表添加新成員                               userList.Add(user);                               AddItemToListBox(string.Format("用戶{0}({1})加入", user.GetName(), user.GetIPEndPoint()));                               string sendString = "Accept," + tcpPort.ToString();                               // 向客戶端發(fā)送應答消息                               SendtoClient(user, sendString);                               AddItemToListBox(string.Format("向{0}({1})發(fā)出:[{2}]", user.GetName(), user.GetIPEndPoint(), sendString));                               for (int i = 0; i < userList.Count; i++)                               {                                   if (userList[i].GetName() != user.GetName())                                   {                                       // 給在線的其他用戶發(fā)送廣播消息                                       // 通知有新用戶加入                                       SendtoClient(userList[i], message);                                   }                               }                                  AddItemToListBox(string.Format("廣播:[{0}]", message));                               break;                           case "logout":                               for (int i = 0; i < userList.Count; i++)                               {                                   if (userList[i].GetName() == splitstring[1])                                   {                                       AddItemToListBox(string.Format("用戶{0}({1})退出",userList[i].GetName(),userList[i].GetIPEndPoint()));                                       userList.RemoveAt(i); // 移除用戶                                   }                               }                               for (int i = 0; i < userList.Count; i++)                               {                                   // 廣播注銷消息                                   SendtoClient(userList[i], message);                               }                               AddItemToListBox(string.Format("廣播:[{0}]", message));                               break;                       }                   }                   catch                  {                       // 發(fā)送異常退出循環(huán)                       break;                   }               }               AddItemToListBox(string.Format("服務線程{0}終止", serverIPEndPoint));           }              // 向客戶端發(fā)送消息           private void SendtoClient(User user, string message)           {               // 匿名方式發(fā)送               sendUdpClient = new UdpClient(0);               byte[] sendBytes = Encoding.Unicode.GetBytes(message);               IPEndPoint remoteIPEndPoint =user.GetIPEndPoint();               sendUdpClient.Send(sendBytes,sendBytes.Length,remoteIPEndPoint);               sendUdpClient.Close();           }                     // 接受客戶端的連接           private void ListenClientConnect()           {               TcpClient newClient = null;               while (true)               {                   try                  {                       newClient = tcpListener.AcceptTcpClient();                       AddItemToListBox(string.Format("接受客戶端{0}的TCP請求",newClient.Client.RemoteEndPoint));                   }                   catch                  {                       AddItemToListBox(string.Format("監(jiān)聽線程({0}:{1})", serverIp, tcpPort));                       break;                   }                      Thread sendThread = new Thread(SendData);                   sendThread.Start(newClient);               }           }              // 向客戶端發(fā)送在線用戶列表信息           // 服務器通過TCP連接把在線用戶列表信息發(fā)送給客戶端           private void SendData(object userClient)           {               TcpClient newUserClient = (TcpClient)userClient;               userListstring = null;               for (int i = 0; i < userList.Count; i++)               {                   userListstring += userList[i].GetName() + ","                      + userList[i].GetIPEndPoint().ToString() + ";";               }                  userListstring += "end";               networkStream = newUserClient.GetStream();               binaryWriter = new BinaryWriter(networkStream);               binaryWriter.Write(userListstring);               binaryWriter.Flush();               AddItemToListBox(string.Format("向{0}發(fā)送[{1}]", newUserClient.Client.RemoteEndPoint, userListstring));               binaryWriter.Close();               newUserClient.Close();           }

客戶端核心代碼:

View Code     // 登錄服務器           private void btnlogin_Click(object sender, EventArgs e)           {               // 創(chuàng)建接受套接字               IPAddress clientIP = IPAddress.Parse(txtLocalIP.Text);               clientIPEndPoint = new IPEndPoint(clientIP, int.Parse(txtlocalport.Text));               receiveUdpClient = new UdpClient(clientIPEndPoint);               // 啟動接收線程               Thread receiveThread = new Thread(ReceiveMessage);               receiveThread.Start();                  // 匿名發(fā)送               sendUdpClient = new UdpClient(0);               // 啟動發(fā)送線程               Thread sendThread = new Thread(SendMessage);               sendThread.Start(string.Format("login,{0},{1}", txtusername.Text, clientIPEndPoint));                  btnlogin.Enabled = false;               btnLogout.Enabled = true;               this.Text = txtusername.Text;           }              // 客戶端接受服務器回應消息            private void ReceiveMessage()           {               IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any,0);               while (true)               {                   try                  {                       // 關閉receiveUdpClient時會產生異常                       byte[] receiveBytes = receiveUdpClient.Receive(ref remoteIPEndPoint);                       string message = Encoding.Unicode.GetString(receiveBytes,0,receiveBytes.Length);                          // 處理消息                       string[] splitstring = message.Split(',');                          switch (splitstring[0])                       {                           case "Accept":                               try                              {                                   tcpClient = new TcpClient();                                   tcpClient.Connect(remoteIPEndPoint.Address, int.Parse(splitstring[1]));                                   if (tcpClient != null)                                   {                                       // 表示連接成功                                       networkStream = tcpClient.GetStream();                                       binaryReader = new BinaryReader(networkStream);                                   }                               }                               catch                              {                                   MessageBox.Show("連接失敗", "異常");                               }                                  Thread getUserListThread = new Thread(GetUserList);                               getUserListThread.Start();                               break;                           case "login":                               string userItem = splitstring[1] + "," + splitstring[2];                               AddItemToListView(userItem);                               break;                           case "logout":                               RemoveItemFromListView(splitstring[1]);                               break;                           case "talk":                               for (int i = 0; i < chatFormList.Count; i++)                               {                                   if (chatFormList[i].Text == splitstring[2])                                   {                                       chatFormList[i].ShowTalkInfo(splitstring[2], splitstring[1], splitstring[3]);                                   }                               }                                  break;                       }                   }                   catch                  {                       break;                   }               }           }              // 從服務器獲取在線用戶列表           private void GetUserList()           {               while (true)               {                   userListstring = null;                   try                  {                       userListstring = binaryReader.ReadString();                       if (userListstring.EndsWith("end"))                       {                           string[] splitstring = userListstring.Split(';');                           for (int i = 0; i < splitstring.Length - 1; i++)                           {                               AddItemToListView(splitstring[i]);                           }                              binaryReader.Close();                           tcpClient.Close();                           break;                       }                   }                   catch                  {                       break;                   }               }           }      // 發(fā)送登錄請求           private void SendMessage(object obj)           {               string message = (string)obj;               byte[] sendbytes = Encoding.Unicode.GetBytes(message);               IPAddress remoteIp = IPAddress.Parse(txtserverIP.Text);               IPEndPoint remoteIPEndPoint = new IPEndPoint(remoteIp, int.Parse(txtServerport.Text));               sendUdpClient.Send(sendbytes, sendbytes.Length, remoteIPEndPoint);               sendUdpClient.Close();           }

程序的運行結果:

首先先運行服務器窗口,在服務器窗口點擊“啟動”按鈕來啟動服務器,然后客戶端首先指定服務器的端口號,修改用戶名(這里也可以不修改,使用默認的也可以),然后點擊“登錄”按鈕來登陸服務器(也就是告訴服務器本地的客戶端地址),然后從服務器端獲得在線用戶列表,界面演示如下:

C#的即時通信程序怎么實現(xiàn)

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

C#的即時通信程序怎么實現(xiàn)

雙方進行聊天時,這里沒有實現(xiàn)像QQ一樣,有人發(fā)信息來在對應的客戶端就有消息提醒的功能的, 所以雙方進行聊天的過程中,每個客戶端都需要在在線用戶列表中點擊聊天的對象來激活聊天對話框(意思就是從圖片中可以看出“天涯”客戶端想和劍癡聊天的話,就在“在線用戶”列表雙擊劍癡來激活聊天窗口,同時“劍癡”客戶端也必須雙擊“天涯”來激活聊天窗口,這樣雙方就看到對方發(fā)來的信息了,(不激活窗口,也是發(fā)送了信息,只是沒有一個窗口來進行顯示)),而且從圖片中也可以看出&mdash;&mdash;此程序支持與多人聊天,即天涯同時與“劍癡”和"大地"同時聊天。

到此,關于“C#的即時通信程序怎么實現(xiàn)”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI