本文源代码下载
上一章我们讲到了如何用TcpListener侦听连接以及如何使用TcpClient建立一个连接并发送消息。
这一章我们将深入讲解如何定义网络通迅协议及如何使用这个协议进行通迅。
首先我们先重构一下前章提到的网络通迅组件。
我们知道在服务器端和客户端都要侦听是否对方发来消息,如果只在主线程中运行,那我们就没法进行其它如UI等方面的工作了。我们将Listen这个方法提出来放到一个基类中。
新建一个类SocketBase。让Server和Client两个类都继承自这个类。将Server类中的Connections属性放到这个类中(因为Client中也可能有多个连接),由于客户端也要侦听
服务器发来的消息,因此我们将_listenningthread和Listenning函数也放到类中。并把private型的变量改为protected以便于继承类可以使用。将Listening函数改为virtual型
以便于子类中可以重写。
下面我们定义网络协议如下:
一个消息体包含消息头和消息体两部分。消息体为字符串型。
消息头包含3部分,前4个字节为消息的总长度,第5个字节表示命令,第6、7两个字节表示协议版本号。按此协议,我们定义Message类,源代码如下:
1
using System;
2![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
namespace SocketLibrary
4![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
5
public class Message
6![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
7![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public enum CommandHeader:byte
{
8
SendMessage = 1
9
}
10
public Connection SendToOrReceivedFrom;
11
public int MessageLength;
12
public CommandHeader Command;
13
public byte MainVersion;
14
public byte SecondVersion;
15![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
16
public string MessageBody;
17![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
18
public Message()
19![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
20
SendToOrReceivedFrom = null;
21
}
22![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public Message(CommandHeader command,byte mainVersion,byte secondVersion,string messageBody):this()
{
23
this.Command = command;
24
this.MainVersion = mainVersion;
25
this.SecondVersion = secondVersion;
26
this.MessageBody = messageBody;
27
}
28
}
我们在Message中增加一个Connection类型的变量是用于存放是要发送的目的或从哪个连接收到的消息。
由于我们在向网络流写入的时候需要写入的是byte数组。我们给Message类增加一个ToBytes方法。返回一个字节数组。
1![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
public byte[] ToBytes()
{
2
this.MessageLength = 7 + SocketFactory.DefaultEncoding.GetByteCount(this.MessageBody);//计算消息总长度。消息头长度为7加上消息体的长度。
3
byte[] buffer = new byte[this.MessageLength];
4
//先将长度的4个字节写入到数组中。
5
BitConverter.GetBytes(this.MessageLength).CopyTo(buffer,0);
6
//将CommandHeader写入到数组中
7
buffer[4] = (byte)this.Command;
8
//将主版本号写入到数组中
9
buffer[5] = (byte)this.MainVersion;
10
//将次版本号写入到数组中
11
buffer[6] = (byte)this.SecondVersion;
12![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
13
//消息头已写完,现在写消息体。
14
SocketFactory.DefaultEncoding.GetBytes(this.MessageBody,0,this.MessageLength - 7, buffer,7);
15
return buffer;
16
}
我们从网络流中读取的字节数组也要转换为Message类。我们用一个静态方法Parse来实现。该方法的参数为Connection。返回一个Message类。
1![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
public static Message Parse(Connection connection)
{
2
Message message = new Message();
3
//先读出前四个字节,即Message长度
4
byte[] buffer = new byte[4];
5![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(connection.NetworkStream.DataAvailable)
{
6
int count = connection.NetworkStream.Read(buffer,0,4);
7![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(count == 4)
{
8
message.MessageLength = BitConverter.ToInt32(buffer,0);
9
}
10
else
11
throw new Exception("网络流长度不正确");
12
}
13
else
14
throw new Exception("目前网络不可读");
15
//读出消息的其它字节
16
buffer = new byte[message.MessageLength - 4];
17![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(connection.NetworkStream.DataAvailable)
{
18
int count = connection.NetworkStream.Read(buffer,0,buffer.Length);
19![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(count == message.MessageLength -4)
{
20
message.Command = (CommandHeader)buffer[0];
21
message.MainVersion = buffer[1];
22
message.SecondVersion = buffer[2];
23![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
24
//读出消息体
25
message.MessageBody = SocketFactory.DefaultEncoding.GetString(buffer,3,buffer.Length - 3);
26
message.SendToOrReceivedFrom = connection;
27![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
28
return message;
29
}
30
else
31
throw new Exception("网络流长度不正确");
32
}
33
else
34
throw new Exception("目前网络不可读");
35
}
36![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
37
}
我们再写一个继承自CollectionBase的类MessageCollection。用于存放消息队列。
1
using System;
2![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
3
namespace SocketLibrary
4![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
{
5
public class MessageCollection:System.Collections.CollectionBase
6![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
7
public MessageCollection()
8![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
9
10
}
11![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public void Add(Message value)
{
12
List.Add(value);
13
}
14![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public Message this[int index]
{
15![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{
16
return List[index] as Message;
17
}
18![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
set
{
19
List[index] = value;
20
}
21
}
22![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public MessageCollection this[Connection connection]
{
23![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
get
{
24
MessageCollection collection = new MessageCollection();
25![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
foreach(Message message in List)
{
26
if(message.SendToOrReceivedFrom == connection)
27
collection.Add(message);
28
}
29
return collection;
30
}
31
}
32
}
33
}
好了。协议制定完了,下面我们修改SocketBase的Listenning函数。当网络流可读时,我们就读出一个message格式的消息。并且在SocketBase中定义ConnectionClose、MessageReceived事件。
并且在SocketBase的Listenning中根据情况触发。
再在SocketBase中增加一个MessageConnection型的属性。表示要发送的消息队列。
我们需要再启动一个线程。用于从消息队列中取出要发送的消息并发送。
最后源代码如下。在这个源代码中在停止时我们没有关闭网络连接。请自行关闭。
在最后的优化中,上面提到的源代码做了一定的修改,请从本文顶端下载源代码查看
1![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
protected virtual void Sendding()
{
2![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
3![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
while(true)
{
4
System.Threading.Thread.Sleep(200);
5![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for(int i = 0 ; i < this.messageQueue.Count ; i++)
{
6![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(this.messageQueue[i].SendToOrReceivedFrom != null)
{
7
this.Send(this.messageQueue[i]);
8
this.OnMessageSent(this,new MessageEventArgs(this.messageQueue[i],this.messageQueue[i].SendToOrReceivedFrom));
9
}
10![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
else
{//对每一个连接都发送此消息
11![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for(int j = 0 ; j < this.Connections.Count ; j++)
{
12
this.Send(this.messageQueue[i],this.Connections[j]);
13
this.OnMessageSent(this,new MessageEventArgs(this.messageQueue[i],this.Connections[j]));
14
}
15
}
16
this.messageQueue[i].Sent = true;
17
}
18
//清除所有已发送消息
19![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
for(int i = this.messageQueue.Count - 1 ; i > -1 ; i--)
{
20
if(this.messageQueue[i].Sent)
21
this.messageQueue.RemoveAt(i);
22
}
23
}
24![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
}catch
{
25
}
26
}
27![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
protected virtual void Listenning()
{
28![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
29![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
while(true)
{
30
System.Threading.Thread.Sleep(200);
31![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
foreach(Connection connection in this._connections)
{
32![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
if(connection.NetworkStream.CanRead && connection.NetworkStream.DataAvailable)
{
33![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
try
{
34
Message message = Message.Parse(connection);
35
this.OnMessageReceived(this,new MessageEventArgs(message,connection));
36
}
37![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
catch(Exception ex)
{
38
connection.NetworkStream.Close();
39
this.OnConnectionClose(this,new ConnectionEventArgs(connection,ex));
40
}
41
}
42
}
43
}
44
}
45![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
catch
{
46
}
47
}
——唐月华