110,567
社区成员
发帖
与我相关
我的任务
分享
public class tongxun
{
public delegate void RecverMsgHandle(string s);
/// <summary>
/// 返回信息产生事件
/// </summary>
public event RecverMsgHandle RecverMsg;
struct pipeobject
{
public NamedPipeServerStream pipe;
public byte[] buf;
}
NamedPipeClientStream pipeClient;
NamedPipeServerStream pipeServer;
string myPipe, ortherPipe;
int Bufsize = 2048; //接收字节最大长度,根据标示自己改
public tongxun(string mypipe, string ortherpipe)
{
myPipe = mypipe;
ortherPipe = ortherpipe;
Thread th = new Thread(new ThreadStart(start));
th.Start();
}
void start()
{
pipeClient = new NamedPipeClientStream("127.0.0.1", ortherPipe, PipeDirection.InOut); //发送信息
pipeServer = new NamedPipeServerStream(myPipe, PipeDirection.InOut, 3, PipeTransmissionMode.Message, PipeOptions.Asynchronous); //接收信息
pipeServer.BeginWaitForConnection(AsyncConnect, pipeServer);
while (true)
{
try
{
pipeClient.Connect();
break;
}
catch
{
}
}
}
public Boolean pipeSendMsg(string s)
{
int i;
string str1;
byte[] buf = System.Text.Encoding.Default.GetBytes(s);
byte[] rbuf = new byte[32];
if (pipeClient.IsConnected)
{
pipeClient.Write(buf, 0, buf.Length);
pipeClient.Flush();
i = pipeClient.Read(rbuf, 0, 32);
str1 = System.Text.Encoding.Default.GetString(rbuf, 0, i);
if (str1 == "ok")
return true;
else
return false;
}
else
{
return false;
}
}
private void AsyncConnect(IAsyncResult ar)
{
NamedPipeServerStream nps = (NamedPipeServerStream)ar.AsyncState;
try
{
nps.EndWaitForConnection(ar);
pipeServer = new NamedPipeServerStream(myPipe, PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
pipeServer.BeginWaitForConnection(AsyncConnect, pipeServer);
pipeobject po = new pipeobject();
po.pipe = nps;
po.buf = new byte[Bufsize];
po.pipe.BeginRead(po.buf, 0, Bufsize, AsyncRead, po);
}
catch
{
nps.Close();
nps.Dispose();
pipeServer = new NamedPipeServerStream(myPipe, PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
pipeServer.BeginWaitForConnection(AsyncConnect, pipeServer);
}
}
private void AsyncRead(IAsyncResult ar)
{
int i;
string s;
pipeobject po = (pipeobject)ar.AsyncState;
try
{
i = po.pipe.EndRead(ar);
s = Encoding.Default.GetString(po.buf, 0, i);
RecverMsg(s);
po.pipe.BeginWrite(Encoding.Default.GetBytes("ok"), 0, 2, AsyncWrite, po);
}
catch
{
po.pipe.Close();
po.pipe.Dispose();
}
}
private void AsyncWrite(IAsyncResult ar)
{
pipeobject po = (pipeobject)ar.AsyncState;
try
{
po.pipe.EndWrite(ar);
po.buf = new byte[Bufsize];
po.pipe.BeginRead(po.buf, 0, Bufsize, AsyncRead, po);
}
catch
{
po.pipe.Close();
po.pipe.Dispose();
}
}
public void Close()
{
pipeClient.Close();
pipeServer.Close();
pipeClient.Dispose();
pipeServer.Dispose();
}
}