选择一个人在C聊天#
考虑一些人在线的信使的情况。 我需要选择一个特定的人进行聊天。 我该如何在C#中这样做呢? 我想要的是通过点击他的名字来选择一个特定的人。之后,无论我输入什么类型的密码,都必须像IP Lanmessenger软件一样发送(希望你已经使用了它)。 有人能帮助我out.Thanks选择一个人在C聊天#
如果你正在建设一个聊天的用户界面和你想在网上看到所有的人典型的UI元素将是一个列表框,然后代码,在项目上的On_Click火灾在盒子里。该代码可以打开另一个UI元素来开始聊天。
获取登录用户列表比较困难。您将需要实施某种Observer/Subscriber模式来处理您正在实施的聊天协议的通知。
GeekPedia在creating a chat client and server in C#上有很棒的系列。
您可以告诉我单击列表框中的项目时触发的事件的名称。 我知道代码上的事件名称应该是On_Click,但属性工具栏中事件列表中的名称是什么? 谢谢 – Avik 2009-05-07 04:30:46
我不认为你想要On_Click,你可能想要SelectedIndexChanged。 – 2009-05-07 13:32:11
如果你想跟踪用户,我建议编码一个服务器应用程序来处理所有的连接。下面是一个简单的例子(注意,这是不是一个完整的例子):
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 18:31:21