// Displays sending with a connected socket
// using the overload that takes a buffer, message size, and socket flags. public static int SendReceiveTest3(Socket server)
{
byte[] msg = Encoding.UTF8.GetBytes("This is a test");
byte[] bytes = new byte[256];
try {
// Blocks until send returns.
int i = server.Send(msg, msg.Length, SocketFlags.None); Console.WriteLine("Sent {0} bytes.", i);
// Get reply from the server.
int byteCount = server.Receive(bytes, server.Available, SocketFlags.None); if (byteCount > 0)
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
catch (SocketException e)
{
Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
return (e.ErrorCode);
}
return 0; }
文本比较的核心就是比较两个给定的文本(可以是字节流等)之间的差异。目前,主流的比较文本之间的差异主要有两大类。一类是基于编辑距离(Edit Distance)的,例如LD算法。一类是基于最长公共子串的(Longest Common Subsequence),例如Needleman/Wunsch算法等。
下面是LD算法的代码,用的是VB2005。代码格式修正于2012年1月6日。Public Class clsLD Private Shared mA() As Char Private Shared mB() As Char
Public Shared Function LD(ByVal A As String, ByVal B As String) As Integer
mA = A.ToCharArray mB = B.ToCharArray
Dim L(A.Length, B.Length) As Integer Dim i As Integer, j As Integer
For i = 1 To A.Length L(i, 0) = i Next For j = 1 To B.Length L(0, j) = j Next
For i = 1 To A.Length For j = 1 To B.Length If mA(i – 1) = mB(j – 1) Then L(i, j) = L(i – 1, j – 1) Else L(i, j) = Min(L(i – 1, j – 1), L(i – 1, j), L(i, j – 1)) + 1 End If Next Next
Return L(A.Length, B.Length) End Function
Public Shared Function Min(ByVal A As Integer, ByVal B As Integer, ByVal C As Integer) As Integer Dim I As Integer = A If I > B Then I = B If I > C Then I = C Return I End Function End Class