如何解决为什么在 2 个服务器运行时交替记录消息?
问题是:如果你启动2个服务器和1个客户端,并尝试向服务器发送一条消息,那么该消息将发送到第一个启动的服务器,第二条消息发送到第二个启动的服务器,将第三条消息发送给第一条消息,依此类推。我不明白为什么会这样?
服务器
namespace Pipes
{
public partial class frmMain : Form
{
private Int32 PipeHandle;
private string PipeName = "\\\\" + Dns.GetHostName() + "\\pipe\\ServerPipe";
private Thread t;
private bool _continue = true;
public frmMain()
{
InitializeComponent();
PipeHandle = DIS.Import.CreateNamedPipe("\\\\.\\pipe\\ServerPipe",DIS.Types.PIPE_ACCESS_DUPLEX,DIS.Types.PIPE_TYPE_BYTE | DIS.Types.PIPE_WAIT,DIS.Types.PIPE_UNLIMITED_INSTANCES,1024,DIS.Types.NMPWAIT_WAIT_FOREVER,(uint)0);
this.Text += " " + PipeName;
t = new Thread(ReceiveMessage);
t.Start();
}
private void ReceiveMessage()
{
string msg = "";
uint realBytesReaded = 0;
while (_continue)
{
if (DIS.Import.ConnectNamedPipe(PipeHandle,0))
{
byte[] buff = new byte[1024];
DIS.Import.FlushFileBuffers(PipeHandle);
DIS.Import.ReadFile(PipeHandle,buff,ref realBytesReaded,0);
msg = Encoding.Unicode.GetString(buff);
rtbMessages.Invoke((MethodInvoker)delegate
{
if (msg != "")
rtbMessages.Text += "\n >> " + msg;
});
DIS.Import.DisconnectNamedPipe(PipeHandle);
Thread.Sleep(500);
}
}
}
private void frmMain_FormClosing(object sender,FormClosingEventArgs e)
{
_continue = false;
if (t != null)
t.Abort();
if (PipeHandle != -1)
DIS.Import.CloseHandle(PipeHandle);
}
}
}
客户
namespace Pipes
{
public partial class frmMain : Form
{
private Int32 PipeHandle;
public frmMain()
{
InitializeComponent();
this.Text += " " + Dns.GetHostName();
}
private void btnSend_Click(object sender,EventArgs e)
{
uint BytesWritten = 0;
byte[] buff = Encoding.Unicode.GetBytes(Dns.GetHostName().ToString() + " >> " + tbMessage.Text);
PipeHandle = DIS.Import.CreateFile(tbPipe.Text,DIS.Types.EFileAccess.GenericWrite,DIS.Types.EFileShare.Read,DIS.Types.ECreationDisposition.OpenExisting,0);
DIS.Import.WriteFile(PipeHandle,Convert.ToUInt32(buff.Length),ref BytesWritten,0);
DIS.Import.CloseHandle(PipeHandle);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。