[英]Selecting a person to chat with in C#
考慮一個LAN Messenger的情況,其中有許多人在線。 我需要選擇一個要聊天的人。 我該如何在C#中進行操作? 我想要的是通過單擊某個人的名字來選擇一個人。此后,我輸入的任何內容都必須像IP Lanmessenger軟件一樣發送(希望您使用此人)。 有人可以幫我嗎。謝謝
如果您想跟蹤用戶,我建議對服務器應用程序進行編碼以處理所有連接。 這是一個簡單的示例(請注意,這不是完整的示例):
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
private TcpListener tcpListener;
private Thread listenerThread;
volatile bool listening;
// Create a client struct/class to handle connection information and names
private List<Client> clients;
// In constructor
clients = new List<Client>();
tcpListener = new TcpListener(IPAddress.Any, 3000);
listening = true;
listenerThread = new Thread(new ThreadStart(ListenForClients));
listenerThread.Start();
// ListenForClients function
private void ListenForClients()
{
// Start the TCP listener
this.tcpListener.Start();
TcpClient tcpClient;
while (listening)
{
try
{
// Suspends while loop till a client connects
tcpClient = this.tcpListener.AcceptTcpClient();
// Create a thread to handle communication with client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleMessage));
clientThread.Start(tcpClient);
}
catch { // Handle errors }
}
}
// Handling messages (Connect? Disconnect? You can customize!)
private void HandleMessage(object client)
{
// Retrieve our client and initialize the network stream
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
// Create our data
byte[] byteMessage = new byte[4096];
int bytesRead;
string message;
string[] data;
// Set our encoder
ASCIIEncoding encoder = new ASCIIEncoding();
while (true)
{
// Retrieve the clients message
bytesRead = 0;
try { bytesRead = clientStream.Read(byteMessage, 0, 4096); }
catch { break; }
// Client had disconnected
if (bytesRead == 0)
break;
// Decode the clients message
message = encoder.GetString(byteMessage, 0, bytesRead);
// Handle the message...
}
}
現在再次注意,這不是一個完整的示例,我知道我已經全力以赴,但是我希望這能給您一個思路。 HandleMessage函數中的消息部分可以是用戶的IP地址(如果他們正在連接到聊天服務器/正在斷開連接)以及要指定的其他參數。 這是我為父親公司編寫的應用程序中的代碼,以便員工可以通過我編寫的自定義CRM相互發送消息。 如果您還有其他問題,請發表評論。
如果您正在構建用於聊天的UI,並且希望看到所有在線用戶,則典型的UI元素將是一個列表框,然后在該框中的項目的On_Click上觸發代碼。 該代碼可以打開另一個UI元素以開始聊天。
獲取登錄用戶列表比較困難。 您將需要實現某種類型的Observer / Subscriber模式來處理來自您正在實現的聊天協議的通知。
GeekPedia有一個很棒的系列文章,介紹如何使用C#創建聊天客戶端和服務器 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.