一个简单的多线程即时通讯程序(类似QQ,MSN)

[翻译]
massivegas著A simple Multi-Threaded Server Client Instant Messenger Application

[简介]
本文实现一个简单的多线程客户/服务器即时通讯应用程序,它将使用TCP连接。允许客户之间及客户和服务器之间,个人消息与会议通信。最终目标是实现象雅虎/msn这样的即时通讯工具。



[库]

我创建一个ChatLibrary,它包含命令及可以着色的消息。

 

public enum Command
{
Login = 0,
PersonalMessage = 1,
ClientList = 2,
Conference = 3,
Logout = 4
};

public class Message
{
string strSender;
string strReceiver;
Command cmdMessageCommand;
string strMessageDetail;
public Message ()
{
}
public Message (byte [] rawMessage)
{
string strRawStringMessage = System.Text.Encoding.ASCII.GetString (rawMessage);
string [] strRawStringMessageArray = strRawStringMessage.Split(new char []{'|'});
this.strSender = strRawStringMessageArray[1];
this.strReceiver = strRawStringMessageArray[2];
this.cmdMessageCommand = (Command) Convert.ToInt32(strRawStringMessageArray[3]);
this.MessageDetail = strRawStringMessageArray[4];
}
...

public byte [] GetRawMessage ()
{
System.Text.StringBuilder sbMessage = new System.Text.StringBuilder ("John");
sbMessage.Append("|");
sbMessage.Append(strSender);
sbMessage.Append("|");
sbMessage.Append(strReceiver);
sbMessage.Append("|");
sbMessage.Append((int)cmdMessageCommand);
sbMessage.Append("|");
sbMessage.Append(strMessageDetail);
sbMessage.Append("|");
return System.Text.Encoding.ASCII.GetBytes(sbMessage.ToString());
}
...




服务器



我创建了一个SocketServer 类,它调用TCPListener.Start() 方法:

 

IPEndPoint endPoint = new IPEndPoint (ipaAddress, iPort);
listener = new TcpListener (endPoint);
listener.Start();



然后,给监听创建一个线程:

 

thrListenForClients = new Thread(new ThreadStart(ListenForClients));
thrListenForClients.Start();



ListenForClients 方法会等待连接,并赋值给一个新的Client 实例:

 

Client acceptClient = new Client();
acceptClient.Socket = listener.AcceptTcpClient();
listenForMessageDelegate = new ListenForMessageDelegate (ListenForMessages);
listenForMessageDelegate.BeginInvoke(acceptClient, new AsyncCallback(ListenForMessagesCallback), "Completed");



Client是一个包含TCPClient的一个类,用于连接:

 

public class Client {
string strName;
TcpClient tcpClient;
public Client()
{
}
public string Name
{
get{return strName;}
set{ this.strName = value;}
}
public TcpClient Socket
{
get{return tcpClient;}
set{ this.tcpClient = value;}
}
public void SendMessage (Message sendMessage)
{
NetworkStream stream = tcpClient.GetStream();
stream.Write(sendMessage.GetRawMessage() , 0, sendMessage.GetRawMessage().Length);
}
}



接下来,再用NetworkStream 读消息:



一旦我们收到消息后,我们就可以做任何想做的了:

 

txtStatus.Text += "\r\n" + strDisplayMessageType + strWriteText.TrimStart(new char[]{'\r','\n'});



我的SocketServer 类使用一些事件,这样使得coding变得更容易:

 

public event ClientConnectedEventHandler ClientConnected;
public event ClientDisconnectingEventHandler ClientDisconnecting;
public event MessageReceivedEventHandler MessageReceived;




[客户端]

客户端基本上与上面一样,创建一个包含TCPListener 的ClientSocket ,然后调用其Connect() 方法:

IPEndPoint serverEndpoint = new IPEndPoint (ipaAddress , iPort);
tcpClient = new TcpClient ();
tcpClient.Connect(serverEndpoint);
thrListenForMessages = new Thread (new ThreadStart(ListenForMessages));
thrListenForMessages.Start();



ListenForMessages 会循环NetworkStream.Read()

 



然后,我们做一些处理,把得来的数据发送一个Message:

另外,我的目标是创建一个象YM/MSN 一样的即时通讯软件,所以,我做了两个UI form:MessengerForm ClientWindowMessengerForm 包含ClientSocket ,并接收消息。根据接收到的消息,调用MessengerWindow 显示文字。

提示:文章中通过Invoke调用界面:
this.Invoke(createNewClientDelegate, new object []{receivedMessage});


posted @ 2008-03-19 13:08  木子博客  阅读(2105)  评论(0编辑  收藏  举报