考虑一个有很多人在线的局域网信使的情况。我需要选择一个特定的人来聊天。我必须如何在 C# 中这样做?我想要的是通过点击他的名字来选择一个特定的人。之后我必须发送我输入的任何内容,就像在 IP Lanmessenger 软件的情况下一样(希望你们已经使用它)。有人可以帮我吗。谢谢
问问题
2568 次
2 回答
3
如果您想跟踪用户,我建议编写一个服务器应用程序来处理所有连接。这是一个简单的例子(注意这不是一个完整的例子):
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 相互发送消息。如果您还有任何问题,请发表评论。
于 2009-05-05T18:48:10.240 回答
0
如果您正在构建用于聊天的 UI,并且您希望看到所有在线的人,典型的 UI 元素将是一个列表框,然后是在框中的项目的 On_Click 上触发的代码。该代码可以打开另一个 UI 元素来开始聊天。
获取登录用户列表更难。您将需要实现某种观察者/订阅者模式来处理来自您正在实现的聊天协议的通知。
GeekPedia 有一个关于在 C# 中创建聊天客户端和服务器的精彩系列。
于 2009-05-05T18:33:57.077 回答