相关文章推荐
爱健身的眼镜  ·  RestTemplate·  3 月前    · 
强悍的书签  ·  JavaScript 学习-34.HTML ...·  4 月前    · 
文雅的数据线  ·  Java 操作 Neo4J ...·  1 年前    · 
试试fastCSharp的TCP调用,支持服务器端对客户端的流操作。
using System;
using System.IO;

namespace fastCSharp.testCase
{
[fastCSharp.setup.cSharp.tcpServer(IsIdentityCommand = true, Host = "127.0.0.1", Port = 12345)]
internal partial class tcpStream
{
private static byte[] buffer;
[fastCSharp.setup.cSharp.tcpServer]
private bool send(Stream stream)
{
byte[] data = new byte[buffer.Length];
using (stream)
{
for (int length, index = 0; index != data.Length; index += length)
{
if ((length = stream.Read(data, index, Math.Min(data.Length - index, data.Length >> 1))) <= 0) return false;
}
}
return fastCSharp.unsafer.memory.Equal(data, buffer);
}
[fastCSharp.setup.cSharp.tcpServer]
private bool send(Stream stream, int value)
{
return value == 1 && send(stream);
}
[fastCSharp.setup.cSharp.tcpServer]
private unsafe bool readFile(string fileName, Stream stream)
{
byte[] data = File.ReadAllBytes(fileName), buffer = new byte[1 << 10];
fixed (byte* dataFixed = data)
{

for (int index = 0, read; index != data.Length; index += read)
{
read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0 || !fastCSharp.unsafer.memory.Equal(buffer, dataFixed + index, read)) return false;
}
}
return true;
}
[fastCSharp.setup.cSharp.tcpServer]
private unsafe void writeFile(string fileName, Stream stream)
{
byte[] data = File.ReadAllBytes(fileName);
for (int index = 0, count; index != data.Length; index += count)
{
stream.Write(data, index, count = Math.Min(data.Length - index, 1 << 10));
}
}

[fastCSharp.setup.testCase]
private static bool testCase()
{
using (fastCSharp.testCase.tcpServer.tcpStream server = new fastCSharp.testCase.tcpServer.tcpStream())
{
if (server.Start())
{
using (fastCSharp.testCase.tcpClient.tcpStream client = new fastCSharp.testCase.tcpClient.tcpStream())
{
buffer = new byte[256];
for (int index = buffer.Length; index != 0; buffer[--index] = (byte)index) ;

using (MemoryStream memoryStream = new MemoryStream(buffer, 0, buffer.Length))
{
if (!client.send(memoryStream)) return false;
}
using (MemoryStream memoryStream = new MemoryStream(buffer, 0, buffer.Length))
{
if (!client.send(memoryStream, 1)) return false;
}

string fileName = @"..\..\tcpStream.cs";
using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
if (!client.readFile(fileName, fileStream)) return false;
}

string bakFileName = fileName + ".bak";
if (File.Exists(bakFileName)) File.Delete(bakFileName);
try
{
using (FileStream fileStream = new FileStream(bakFileName, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
client.writeFile(fileName, fileStream);
}
if (!fastCSharp.unsafer.memory.Equal(File.ReadAllBytes(fileName), File.ReadAllBytes(bakFileName))) return false;
}
finally { File.Delete(bakFileName); }

return true;
}
}
}
return false;
}
}
}