the question is: if you start 2 servers and 1 client, and try to send a message to the server, then the message is sent to the server that is launched first, and the second message to the one that is launched second, the third message to the first, and so on. I can't understand why this is happening?
Server
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, 0, 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, 1024, ref realBytesReaded, 0);
msg = Encoding.Unicode.GetString(buff);
rtbMessages.Invoke((MethodInvoker)delegate
{
if (msg != "")
rtbMessages.Text += "
>> " + 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);
}
}
}
Client
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, 0, DIS.Types.ECreationDisposition.OpenExisting, 0, 0);
DIS.Import.WriteFile(PipeHandle, buff, Convert.ToUInt32(buff.Length), ref BytesWritten, 0);
DIS.Import.CloseHandle(PipeHandle);
}
}
}
question from:
https://stackoverflow.com/questions/65942765/why-is-the-message-recorded-alternately-when-2-servers-are-running 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…