Previously, I wrote an introduction to some of the common functions and features of TCP and used the code as an example, and finally developed an EasyTcp4Net TCP tool library, whose most important feature is the use of some of the high-performance libraries provided by Microsoft data structures to deal with TCP data.
Recently resigned to stay at home, there is nothing to do, the use of their own TCP communication library based on the development of a sample chat program, features include, text sending, picture sending, disconnect and reconnect, message sent to confirm the success of the message sent to the message failed to send prompts.
typical example
Send a message to yourself
Message received.
Send Picture
Message being sent
relink
Send Failure
Packet structure and unpacking
Define the packet structure
The packet structure defines the complete data structure for sending one data at a time, and we define the packet body length in the packet header to solve the problem of sticky and broken packets.
The packets are sent using a simple serialization into byte arrays.
[StructLayout()]
public class Message<TBody> : IMsssage<TBody> where TBody : Packet
{
//packet packet length 4nibbles
public int BodyLength { get; private set; }
//Message Type 4nibbles
public MessageType MessageType { get; set; }
public TBody? Body { get; set; }
private Message<TBody> Deserialize(byte[] bodyData)
{
var bodyStr = (bodyData);
Body = <TBody>(bodyStr);
return this;
}
public static Message<TBody> FromBytes(ReadOnlyMemory<byte> data)
{
Message<TBody> packet = new Message<TBody>();
= BinaryPrimitives.ReadInt32BigEndian((0, 4).Span);
= (MessageType)BinaryPrimitives.ReadInt32BigEndian((4, 4).Span);
((8, ).());
return packet;
}
public byte[] Serialize()
{
var Length = 4 + 4;
var bodyArray = ((Body));
BodyLength = ;
Length += ;
byte[] result = new byte[Length];
result.AddInt32(0, );
result.AddInt32(4, (int)MessageType);
(bodyArray, 0, result, 8, );
return result;
}
public TBody GetBody()
{
return Body;
}
}
public interface IMsssage <out TBody> where TBody : Packet
{
public TBody GetBody();
}
We call on the server side and on the client side based on the data structure we defined for theEasyTcp4NetFixed packet headers provided to parse packets
_easyTcpClient.SetReceiveFilter(new FixedHeaderPackageFilter(8, 0, 4, false));
Text/Image Sending
We can define the message base class and extend it with two message classes, one for text messages and one for image messages.
public class SendMessagePacket : Packet
{
public string MessageId { get; set; } = ().ToString();
public string From { get; set; }
public string To { get; set; }
}
Picture News
public class SendImageMessagePacket : SendMessagePacket
{
public byte[] Data { get; set; }
public string FileName { get; set; }
}
text message
public class SendTextMessagePacket : SendMessagePacket
{
public string Text { get; set; }
}
We also need to add the relevant text and image ViewModel to the interface
Send a message, the sender can immediately add the message to the chat interface, and then wait to receive the message they send from the server, according to the status of the message to determine whether the message is sent successfully, waiting for the time you can set the message to send the interface status display, the logic of this message and WeChat is basically the same as the logic of sending messages.
Handling of disconnections
utilizationEasyTcp4NetDisconnection events are provided to make it very easy for the server to know that the client is suddenly disconnected, or the client to know that the connection to the server is broken.
client (computing)
_easyTcpClient.OnDisConnected += async (obj, e) =>
{
Title = Title + _disConnectTip;
await ReConnectAsync();
};
The main thing is the mechanism that triggers the reconnection.
server-side
_easyTcpServer.OnClientConnectionChanged += (obj, e) =>
{
if ( == )
{
_accounts.TryRemove(, out var account);
}
};
The main thing is to remove the user from the online list.
summarize
Overall there are more details to consider when making a chat software.
Example Address:/BruceQiu1996/EasyChat