using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace LocalServer
{
public class PipelineServer
{
Thread pipelineThread;
bool isOn = true;
public PipelineServer(bool isSend)
{
if (isSend)
pipelineThread = new Thread(pipelineSend);
else
pipelineThread = new Thread(pipelinRecive);
//pipelineThread.IsBackground = true;
}
void pipelinRecive()
{
try
{
while (isOn)
{
using (NamedPipeServerStream namedPipeServer = new NamedPipeServerStream("TeacherPipeServer", PipeDirection.InOut, 1))
{
using (StreamReader sr = new StreamReader(namedPipeServer))
{
namedPipeServer.WaitForConnection();
string kk = sr.ReadToEnd();
Console.WriteLine("@@@@@@@@@@" + kk);
}
}
}
}
catch (Exception e)
{
throw e;
}
}
Queue<string> poopoo = new Queue<string>();
void pipelineSend()
{
try
{
while (isOn)
{
if (poopoo.Count > 0)
{
using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream(".", "TeacherPipeServer", PipeDirection.InOut, PipeOptions.WriteThrough | PipeOptions.Asynchronous, System.Security.Principal.TokenImpersonationLevel.None, HandleInheritability.None))
{
namedPipeClient.Connect();
using (StreamWriter sw = new StreamWriter(namedPipeClient))
{
sw.WriteLine(poopoo.Dequeue());
}
}
}
}
}
catch (Exception e)
{
throw e;
}
}
public void Start()
{
pipelineThread.Start();
}
public void Close()
{
isOn = false;
poopoo.Clear();
if (pipelineThread != null)
{
pipelineThread.Interrupt();
pipelineThread.Abort();
pipelineThread = null;
}
}
public void AddSendMsg(string information)
{
poopoo.Enqueue(information);
}
}
}
Unity中使用管道通信(NamedPipeServerStream 与 NamedPipeClientStream )
于 2024-03-20 18:05:11 首次发布