考虑一个局域网信使的情况,那里有很多人在线。我需要选择一个特定的人来聊天。我应该如何在C#中这样做呢?我想要的是选择一个特定的人,点击他的name.After,我输入的任何东西都必须被发送,就像在IPLan信使软件的情况下一样(希望你们已经使用了它)。有人能帮我吗out.Thanks
发布于 2009-05-05 10:48:10
如果希望跟踪用户,我建议编写服务器应用程序以处理所有连接。下面是一个快速示例(注意,这不是一个完整的示例):
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-05 10:33:57
如果您正在构建用于聊天的UI,并且希望看到所有联机人员,则典型的UI元素将是一个列表框,然后是在框中某个项目的On_Click上触发的代码。该代码可以打开另一个UI元素来开始聊天。
获取登录用户列表比较困难。您需要实现某种观察者/订阅者模式来处理来自正在实现的聊天协议的通知。
GeekPedia在在C#中创建聊天客户端和服务器上有一个很棒的系列。
https://stackoverflow.com/questions/826213
复制相似问题