本文整理汇总了C#中System.IO.Pipes.NamedPipeClientStream.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# NamedPipeClientStream.Connect方法的具体用法?C# NamedPipeClientStream.Connect怎么用?C# NamedPipeClientStream.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.Pipes.NamedPipeClientStream
的用法示例。
在下文中一共展示了NamedPipeClientStream.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendMessage
public static void SendMessage(String optionVal)
{
using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "RipplePipe", PipeDirection.Out, PipeOptions.Asynchronous))
{
try
{
pipeClient.Connect(2000);
}
catch (Exception)
{
//Try once more
try
{
pipeClient.Connect(5000);
}
catch (Exception)
{
return;
}
}
//Connected to the server or floor application
using (StreamWriter sw = new StreamWriter(pipeClient))
{
sw.Write(optionVal);
}
}
}
示例2: SNINpHandle
public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject)
{
_targetServer = serverName;
_callbackObject = callbackObject;
_writeScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler;
_writeTaskFactory = new TaskFactory(_writeScheduler);
try
{
_pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut, PipeOptions.WriteThrough, Security.Principal.TokenImpersonationLevel.None);
bool isInfiniteTimeOut = long.MaxValue == timerExpire;
if (isInfiniteTimeOut)
{
_pipeStream.Connect(Threading.Timeout.Infinite);
}
else
{
TimeSpan ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
_pipeStream.Connect((int)ts.TotalMilliseconds);
}
}
catch(TimeoutException te)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnTimeoutError, te);
_status = TdsEnums.SNI_WAIT_TIMEOUT;
return;
}
catch(IOException ioe)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe);
_status = TdsEnums.SNI_ERROR;
return;
}
if (!_pipeStream.IsConnected || !_pipeStream.CanWrite || !_pipeStream.CanRead)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty);
_status = TdsEnums.SNI_ERROR;
return;
}
_sslOverTdsStream = new SslOverTdsStream(_pipeStream);
_sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
_stream = _pipeStream;
_status = TdsEnums.SNI_SUCCESS;
}
示例3: SendBreakRequest
public static void SendBreakRequest()
{
using (NamedPipeClientStream client = new NamedPipeClientStream(PIPENAME)) {
client.Connect();
client.Write(BREAK, 0, BREAK.Length);
}
}
示例4: Main
static int Main(string[] args)
{
if (args.Length != 1)
{
return 1;
}
var pipeName = args[0];
//Console.WriteLine(nameof(pipeName) + " = " + pipeName);
using (var pipeClient = new NamedPipeClientStream(pipeName))
{
pipeClient.Connect();
// Receive meta data first.
var messageTypeCommunicator = new CodeShardCommunicator<Type>(pipeClient);
var messageType = messageTypeCommunicator.Receive();
var entryPointCommunicator = new CodeShardCommunicator<object>(pipeClient);
var entryPointInstance = entryPointCommunicator.Receive();
// Get run method for the hosted user code.
var entryPointType = entryPointInstance.GetType();
var expectedInterfaceType = typeof(ICodeShardEntryPoint<>).MakeGenericType(messageType);
var runMethodInfo = expectedInterfaceType.GetMethods()[0];
// Create communicator instance for the hosted user code.
var communicatorType = typeof(CodeShardCommunicator<>).MakeGenericType(messageType);
var communicatorInstance = Activator.CreateInstance(communicatorType, pipeClient);
runMethodInfo.Invoke(entryPointInstance, new object[] { communicatorInstance });
}
return 0;
}
示例5: DxDeviceCtrl
public DxDeviceCtrl()
{
KeybdPipeSwCollection=new Collection<StreamWriter>();
var id = 0;
bool failed = false;
for (id = 0; false == failed; ++id)
{
var KeybdPipe = new NamedPipeClientStream(".", "DxKeybdPipe" + id.ToString(), PipeDirection.Out);
try
{
KeybdPipe.Connect(50);
if (true == KeybdPipe.IsConnected)
{
var KeybdPipeSW = new StreamWriter(KeybdPipe);
KeybdPipeSW.AutoFlush = true;
KeybdPipeSwCollection.Add(KeybdPipeSW);
}
else
{
failed = true;
}
}
catch (Exception )
{
failed = true;
}
}
}
示例6: PipesWriter
private static void PipesWriter(string pipeName)
{
try
{
using (var pipeWriter = new NamedPipeClientStream("TheRocks", pipeName, PipeDirection.Out))
{
pipeWriter.Connect();
WriteLine("writer connected");
bool completed = false;
while (!completed)
{
string input = ReadLine();
if (input == "bye") completed = true;
byte[] buffer = Encoding.UTF8.GetBytes(input);
pipeWriter.Write(buffer, 0, buffer.Length);
}
}
WriteLine("completed writing");
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
}
示例7: Connect
public void Connect(string pipeName, string serverName = ".", int timeout = 2000)
{
NamedPipeClientStream pipeStream = null;
try
{
pipeStream = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut,
PipeOptions.Asynchronous, TokenImpersonationLevel.Impersonation);
pipeStream.Connect(timeout);
using (var stringStream = new StringStream(pipeStream))
{
if (OnConnected != null)
{
OnConnected(stringStream);
}
}
}
catch (Exception exception)
{
if (OnErrorOcurred != null)
{
OnErrorOcurred(exception);
}
}
finally
{
if (pipeStream != null && pipeStream.IsConnected)
{
pipeStream.Flush();
pipeStream.Close();
}
}
}
示例8: ThreadStartClient
public void ThreadStartClient(object obj)
{
// Ensure that we only start the client after the server has created the pipe
ManualResetEvent SyncClientServer = (ManualResetEvent)obj;
// Only continue after the server was created -- otherwise we just fail badly
// SyncClientServer.WaitOne();
using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(pipeName))
{
// The connect function will indefinately wait for the pipe to become available
// If that is not acceptable specify a maximum waiting time (in ms)
pipeStream.Connect(5000);
//Console.WriteLine("[Client] Pipe connection established");
using (StreamWriter sw = new StreamWriter(pipeStream))
{
////sw.AutoFlush = true;
if (Environment.GetCommandLineArgs().Length >= 2)
{
string fname = Environment.GetCommandLineArgs()[1];
sw.WriteLine(fname);
sw.Flush();
}
}
}
}
示例9: Close
public void Close()
{
Console.WriteLine(string.Format("closing pipe server {0}...", PipeName));
m_closing = true;
//emulate new client connected to resume listener thread
using (NamedPipeClientStream fakeClient = new NamedPipeClientStream(".", PipeName, PipeDirection.In))
{
try
{
fakeClient.Connect(100);
fakeClient.Close();
}
catch
{
//server was stopped already
}
}
if (m_listenerThread != null && m_listenerThread.IsAlive)
{
if (!m_listenerThread.Join(5000))
{
m_listenerThread.Abort();
}
}
m_listenerThread = null;
Console.WriteLine(string.Format("disconnecting clients from pipe {0}...", PipeName));
while (m_pipeStreams.Count > 0)
{
DisconnectClient(m_pipeStreams[0]);
}
Console.WriteLine(string.Format("Pipe server {0} stopped OK", PipeName));
}
示例10: InvokeFunc
/// <summary>
/// Calls method with one parameter and result. Deserializes parameter and serialize result.
/// </summary>
/// <param name="type">Type containing method</param>
/// <param name="methodName">Name of method to call</param>
/// <param name="pipeName">Name of pipe to pass parameter and result</param>
static void InvokeFunc(Type type, string methodName, string pipeName)
{
using (var pipe = new NamedPipeClientStream(pipeName))
{
pipe.Connect();
var formatter = new BinaryFormatter();
ProcessThreadParams pars;
var lengthBytes = new byte[4];
pipe.Read(lengthBytes, 0, 4);
var length = BitConverter.ToInt32(lengthBytes, 0);
var inmemory = new MemoryStream(length);
var buf = new byte[1024];
while (length != 0)
{
var red = pipe.Read(buf, 0, buf.Length);
inmemory.Write(buf, 0, red);
length -= red;
}
inmemory.Position = 0;
try
{
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
return type.Assembly;
};
pars = (ProcessThreadParams)formatter.Deserialize(inmemory);
var method = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, null, pars.Types, null);
if (method == null) throw new InvalidOperationException("Method is not found: " + methodName);
if (pars.Pipe != null)
{
var auxPipe = new NamedPipeClientStream(pars.Pipe);
auxPipe.Connect();
for (int i = 0; i < pars.Parameters.Length; i++)
if (pars.Parameters[i] is PipeParameter) pars.Parameters[i] = auxPipe;
}
object result = method.Invoke(pars.Target, pars.Parameters);
var outmemory = new MemoryStream();
formatter.Serialize(outmemory, ProcessThreadResult.Successeded(result));
outmemory.WriteTo(pipe);
}
catch (TargetInvocationException e)
{
formatter.Serialize(pipe, ProcessThreadResult.Exception(e.InnerException));
throw e.InnerException;
}
catch (Exception e)
{
formatter.Serialize(pipe, ProcessThreadResult.Exception(e));
throw;
}
}
}
示例11: NamedPipeCommunicationChannel
/// <summary>
/// Initializes a new instance of the <see cref="NamedPipeCommunicationChannel" /> class.
/// </summary>
/// <param name="endPoint">The end point.</param>
/// <param name="pipeStream">An existing pipe stream or <c>null</c> to create client.</param>
public NamedPipeCommunicationChannel(NamedPipeEndPoint endPoint, PipeStream pipeStream = null)
{
_endPoint = endPoint;
if (pipeStream != null) _pipeStream = pipeStream;
else
{
var client = new NamedPipeClientStream(".", endPoint.Name, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough);
// connect overload with timeout is extremely processor intensive
int elapsed = 0, connectionTimeout = endPoint.ConnectionTimeout * 1000;
CONNECT:
try
{
client.Connect(0);
}
catch (TimeoutException)
{
Thread.Sleep(CONNECT_ATTEMPT_INTERVAL_MS);
if (endPoint.ConnectionTimeout != Timeout.Infinite && (elapsed += CONNECT_ATTEMPT_INTERVAL_MS) > connectionTimeout)
throw new TimeoutException("The host failed to connect. Timeout occurred.");
goto CONNECT;
}
_pipeStream = client;
}
_buffer = new byte[ReceiveBufferSize];
_syncLock = new object();
}
示例12: MouseCtrl
public MouseCtrl()
{
var npipe = new NamedPipeClientStream(".", "mGetCursorPosServerPipe0", PipeDirection.Out);
npipe.Connect();
MousePosPipeSW = new StreamWriter(npipe);
MousePosPipeSW.AutoFlush = true;
}
示例13: process
void process(object o)
{
try
{
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream(".", "testpipe", PipeDirection.In))
{
// Connect to the pipe or wait until the pipe is available.
Console.Write("Attempting to connect to pipe...");
pipeClient.Connect();
Console.WriteLine("Connected to pipe.");
Console.WriteLine("There are currently {0} pipe server instances open.",
pipeClient.NumberOfServerInstances);
using (StreamReader sr = new StreamReader(pipeClient))
{
// Display the read text to the console
string temp;
while (true)
{
if ((temp = sr.ReadLine()) != null)
{
Console.WriteLine("Received from server: {0}", temp);
}
}
}
}
}
catch (Exception ex)
{
}
}
示例14: Send
public string Send(string sendStr, string pipeName, int timeOut = 1000)
{
try
{
NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut);
pipeStream.Connect(timeOut);
var sr = new StreamReader(pipeStream);
var sw = new StreamWriter(pipeStream);
sw.WriteLine(sendStr);
sw.Flush();
string temp = sr.ReadToEnd();
return temp;
}
catch (Exception oEX)
{
MessageBox.Show("Error :" + oEX.Message);
Debug.WriteLine(oEX.Message);
}
return "";
}
示例15: GetActiveServerList
public static List<Server> GetActiveServerList()
{
List<Server> serverList = new List<Server>();
List<int> pids = new List<int>();
foreach (Process p in Process.GetProcessesByName(ServerName))
{
pids.Add(p.Id);
}
foreach (int pid in pids)
{
using (NamedPipeClientStream npc = new NamedPipeClientStream(".", "wss" + pid, PipeDirection.In))
{
try
{
npc.Connect(1500);
using (StreamReader sr = new StreamReader(npc))
{
string data = sr.ReadToEnd();
string[] chunks = data.Split(':');
if (chunks.Length != 2) continue;
serverList.Add(new Server() { Name = chunks[0], Port = int.Parse(chunks[1]), Pid = pid });
}
}
catch (TimeoutException)
{
continue; // Since this one timed out, we don't care about it, so move on to the next one.
}
}
}
return serverList;
}