即時通訊系統開發 編程
在咱們的生活中常用即時通訊的軟件,咱們常常接觸到的有: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平臺開發。
程序實現
- View Code
- // 啓動服務器
- // 根據博客中協議的設計部分
- // 客戶端先向服務器發送登陸請求,而後經過服務器返回的端口號
- // 再與服務器創建鏈接
- // 因此啓動服務按鈕事件中有兩個套接字:一個是接收客戶端信息套接字和
- // 監聽客戶端鏈接套接字
- private void btnStart_Click(object sender, EventArgs e)
- {
- // 建立接收套接字
- 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;
- // 隨機指定監聽端口
- Random random = new Random();
- tcpPort = random.Next(port + 1, 65536);
- // 建立監聽套接字
- tcpListener = new TcpListener(serverIp, tcpPort);
- tcpListener.Start();
- // 啓動監聽線程
- Thread listenThread = new Thread(ListenClientConnect);
- listenThread.Start();
- AddItemToListBox(string.Format("服務器線程{0}啓動,監聽端口{1}",serverIPEndPoint,tcpPort));
- }
- // 接收客戶端發來的信息
- 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));
- // 處理消息數據
- // 根據協議的設計部分,從客戶端發送來的消息是具備必定格式的
- // 服務器接收消息後要對消息作處理
- string[] splitstring = message.Split(',');
- // 解析用戶端地址
- string[] splitsubstring = splitstring[2].Split(':');
- IPEndPoint clientIPEndPoint = new IPEndPoint(IPAddress.Parse(splitsubstring[0]), int.Parse(splitsubstring[1]));
- switch (splitstring[0])
- {
- // 若是是登陸信息,向客戶端發送應答消息和廣播有新用戶登陸消息
- 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();
- // 向客戶端發送應答消息
- SendtoClient(user, sendString);
- AddItemToListBox(string.Format("向{0}({1})發出:[{2}]", user.GetName(), user.GetIPEndPoint(), sendString));
- for (int i = 0; i < userList.Count; i++)
- {
- if (userList[i].GetName() != user.GetName())
- {
- // 給在線的其餘用戶發送廣播消息
- // 通知有新用戶加入
- 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
- {
- // 發送異常退出循環
- break;
- }
- }
- AddItemToListBox(string.Format("服務線程{0}終止", serverIPEndPoint));
- }
- // 向客戶端發送消息
- private void SendtoClient(User user, string message)
- {
- // 匿名方式發送
- 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("監聽線程({0}:{1})", serverIp, tcpPort));
- break;
- }
- Thread sendThread = new Thread(SendData);
- sendThread.Start(newClient);
- }
- }
- // 向客戶端發送在線用戶列表信息
- // 服務器經過TCP鏈接把在線用戶列表信息發送給客戶端
- 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}發送[{1}]", newUserClient.Client.RemoteEndPoint, userListstring));
- binaryWriter.Close();
- newUserClient.Close();
- }
客戶端核心代碼:
- View Code
- // 登陸服務器
- private void btnlogin_Click(object sender, EventArgs e)
- {
- // 建立接受套接字
- 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();
- // 匿名發送
- sendUdpClient = new UdpClient(0);
- // 啓動發送線程
- 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;
- }
- }
- }
- // 發送登陸請求
- 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();
- }
程序的運行結果:
首先先運行服務器窗口,在服務器窗口點擊「啓動」按鈕來啓動服務器,而後客戶端首先指定服務器的端口號,修改用戶名(這裏也能夠不修改,使用默認的也能夠),而後點擊「登陸」按鈕來登錄服務器(也就是告訴服務器本地的客戶端地址),而後從服務器端得到在線用戶列表,界面演示以下:
而後用戶能夠雙擊在線用戶進行聊天(此程序支持與多人進行聊天),下面是功能的演示圖片:
雙方進行聊天時,這裏沒有實現像QQ同樣,有人發信息來在對應的客戶端就有消息提醒的功能的, 因此雙方進行聊天的過程當中,每一個客戶端都須要在在線用戶列表中點擊聊天的對象來激活聊天對話框(意思就是從圖片中能夠看出「天涯」客戶端想和劍癡聊天的話,就在「在線用戶」列表雙擊劍癡來激活聊天窗口,同時「劍癡」客戶端也必須雙擊「天涯」來激活聊天窗口,這樣雙方就看到對方發來的信息了,(不激活窗口,也是發送了信息,只是沒有一個窗口來進行顯示)),並且從圖片中也能夠看出——此程序支持與多人聊天,即天涯同時與「劍癡」和"大地"同時聊天。
在此基礎上,能夠實現程序更多的功能,要靠插件完成
end