Beispiel #1
0
 void _DoConnPinSM()
 {
     if (null == pinhost)
     {
         pinhost = "localhost";
     }
     if (null != pinstm)
     {
         try
         {
             pinstm.Close();
         }
         catch
         {
         }
         pinstm = null;
     }
     try
     {
         System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                                                        System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
         sock.Connect(pinhost, 55906);
         pinstm = new System.Net.Sockets.NetworkStream(sock, true); // ownsSocket=true
     }
     catch (Exception e)
     {
         throw new Exception("Unable to connect to MemCachePin service [ensure MemCachePin Windows services are installed and running]", e);
     }
 }
Beispiel #2
0
 void _open()
 {
     System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                                                    System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
     System.Net.Sockets.NetworkStream ntsm = null;
     try
     {
         sock.Connect(Surrogate.MasterHost, 55900);
         ntsm = new XNetworkStream(sock);
         ntsm.WriteByte((byte)'J'); //hand shake with surrogate
         if (ntsm.ReadByte() == (byte)'+')
         {
             this.sock = sock;
             this.ntsm = ntsm;
         }
         else
         {
             throw new Exception("CriticalSection.Create() handshake failed.");
         }
     }
     catch
     {
         if (ntsm != null)
         {
             ntsm.Close();
             ntsm = null;
         }
         sock.Close();
         sock = null;
         throw;
     }
 }
Beispiel #3
0
        public bool sendData(string adr, int port, byte[] donnees, int timeout)
        {
            System.Net.Sockets.TcpClient     client = new System.Net.Sockets.TcpClient();
            System.Net.Sockets.NetworkStream ns     = null;

            try
            {
                client.Connect(adr, port);
                if (!client.Connected)
                {
                    throw new Exception("Pas de connexion");
                }
                client.SendTimeout = timeout;
                ns = client.GetStream();
                ns.Write(donnees, 0, donnees.Length);
                return(true);
            }
            catch { }
            finally
            {
                if (ns != null)
                {
                    ns.Close();
                }
                client.Close();
            }
            return(false);
        }
        public static void SendTCP(string host, int port, string msg)
        {
            System.Net.Sockets.TcpClient tcp;
            try
            {
                tcp = new System.Net.Sockets.TcpClient(host, port);
            }
            catch
            {
                return;
            }

            try
            {
                System.Net.Sockets.NetworkStream ns = tcp.GetStream();

                try
                {
                    ns.ReadTimeout  = 10000;
                    ns.WriteTimeout = 10000;

                    Encoding enc       = Encoding.UTF8;
                    byte[]   sendBytes = enc.GetBytes(msg + '\n');
                    ns.Write(sendBytes, 0, sendBytes.Length);
                }
                finally
                {
                    ns.Close();
                }
            }
            finally
            {
                tcp.Close();
            }
        }
Beispiel #5
0
        private object sendAndReceivedData(string adr, int port, byte[] donnees, int timeout)
        {
            System.Net.Sockets.TcpClient     client = new System.Net.Sockets.TcpClient();
            System.Net.Sockets.NetworkStream ns     = null;

            try
            {
                client.Connect(adr, port);
                if (!client.Connected)
                {
                    throw new Exception("Pas de connexion");
                }
                client.SendTimeout    = timeout;
                client.ReceiveTimeout = timeout;
                ns = client.GetStream();
                ns.Write(donnees, 0, donnees.Length);
                byte[] data = new byte[client.ReceiveBufferSize];
                return(ns.Read(data, 0, client.ReceiveBufferSize));
            }
            catch { }
            finally
            {
                if (ns != null)
                {
                    ns.Close();
                }
                client.Close();
            }
            return(null);
        }
Beispiel #6
0
 public void Connect(string surrogatehost)
 {
     System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                                                    System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
     try
     {
         sock.Connect(surrogatehost, 55905);
         netstm = new XNetworkStream(sock);
         netstm.WriteByte(199);
         if (netstm.ReadByte() != 199 / 3)
         {
             throw new Exception("DFS protocol did not respond correctly to handshake");
         }
     }
     catch
     {
         if (netstm != null)
         {
             netstm.Close();
             netstm = null;
         }
         sock.Close();
         sock = null;
         throw;
     }
     buf = new byte[1024 * 4];
 }
        public void Disconnect()
        {
            if (_bluetoothClient == null)
            {
                return;
            }

            try
            {
                if (_bluetoothClient != null)
                {
                    if (_bluetoothStream != null)
                    {
                        _bluetoothStream.ReadTimeout  = 500;
                        _bluetoothStream.WriteTimeout = 500;
                        _bluetoothStream.Close();
                    }

                    if (_bluetoothClient.Connected)
                    {
                        _bluetoothClient.Close();
                    }
                    _bluetoothClient.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #8
0
        public void Dispose()
        {
            try
            {
                if (_ClientStream != null)
                {
                    _ClientStream.Close();
                }

                if (_Client != null)
                {
                    _Client.Close();
                }

                if (_Async)
                {
                    if (_Thread != null)
                    {
                        if (!ThreadClosed)
                        {
                            _Thread.Abort();
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                _ClientStream = null;
                _Client       = null;
                _Thread       = null;
            }
        }
Beispiel #9
0
        public void Close()
        {
            --RefCount;
            //Debug.Log("TcpClients: Destroy " + RefCount);

            try
            {
                if (_stream != null)
                {
                    _stream.Close();
                }

                if (_net != null)
                {
                    _net.Close();
                }

                if (_client != null)
                {
                    _client.Close();
                }

                if (_async != null)
                {
                    _async = null;
                }
            }
            catch
            {
            }
            _client = null;
            _stream = null;
            _async  = null;
            _net    = null;
        }
Beispiel #10
0
 public void Connect(string surrogatehost)
 {
     System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
         System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
     try
     {
         sock.Connect(surrogatehost, 55905);
         netstm = new XNetworkStream(sock);
         netstm.WriteByte(199);
         if (netstm.ReadByte() != 199 / 3)
         {
             throw new Exception("DFS protocol did not respond correctly to handshake");
         }
     }
     catch
     {
         if (netstm != null)
         {
             netstm.Close();
             netstm = null;
         }
         sock.Close();
         sock = null;
         throw;
     }
     buf = new byte[1024 * 4];
 }
Beispiel #11
0
 /// <summary>
 /// Disconnect
 /// </summary>
 /// <returns></returns>
 public int Disconnect()
 {
     if (IsConnected)
     {
         try
         {
             core.DebugLog("Closing");
             if (streamWriter != null)
             {
                 streamWriter.Close();
                 streamWriter.Dispose();
                 streamWriter = null;
             }
             if (streamReader != null)
             {
                 streamReader.Close();
                 streamReader.Dispose();
                 streamReader = null;
             }
             if (networkStream != null)
             {
                 networkStream.Close();
                 networkStream.Dispose();
                 networkStream = null;
             }
             connected = false;
         }
         catch (Exception fail)
         {
             core.handleException(fail);
         }
     }
     return(0);
 }
Beispiel #12
0
        public static CriticalSection Create(string lockname)
        {
            if (null == lockname)
            {
                if (currentSection != null)
                {
                    return currentSection;
                }
            }
            else
            {
                if (0 == lockname.Length)
                {
                    throw new Exception("Empty lock name is invalid");
                }
            }

            System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
            System.Net.Sockets.NetworkStream ntsm = null;
            try
            {
                ////sock.Connect(Surrogate.MasterHost, 55900);
                sock.Connect(DO5_Surrogate_LocateMasterHost(".."), 55900);
                ntsm = new XNetworkStream(sock);
                ntsm.WriteByte((byte)'J'); //hand shake with surrogate
                if (ntsm.ReadByte() == (byte)'+')
                {
                    CriticalSection sec = new CriticalSection();
                    sec.sock = sock;
                    sec.ntsm = ntsm;
                    sec.hasLock = false;
                    if (null == lockname)
                    {
                        currentSection = sec;
                    }
                    else
                    {
                        sec.locknamebytes = Encoding.UTF8.GetBytes(lockname);
                    }
                    return sec;
                }
                else
                {
                    throw new Exception("CriticalSection.Create() handshake failed.");
                }
            }
            catch
            {
                if (ntsm != null)
                {
                    ntsm.Close();
                    ntsm = null;
                }
                sock.Close();
                sock = null;
                throw;
            }
        }
Beispiel #13
0
        public static CriticalSection Create(string lockname)
        {
            if (null == lockname)
            {
                if (currentSection != null)
                {
                    return(currentSection);
                }
            }
            else
            {
                if (0 == lockname.Length)
                {
                    throw new Exception("Empty lock name is invalid");
                }
            }

            System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                                                           System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
            System.Net.Sockets.NetworkStream ntsm = null;
            try
            {
                ////sock.Connect(Surrogate.MasterHost, 55900);
                sock.Connect(DO5_Surrogate_LocateMasterHost(".."), 55900);
                ntsm = new XNetworkStream(sock);
                ntsm.WriteByte((byte)'J'); //hand shake with surrogate
                if (ntsm.ReadByte() == (byte)'+')
                {
                    CriticalSection sec = new CriticalSection();
                    sec.sock    = sock;
                    sec.ntsm    = ntsm;
                    sec.hasLock = false;
                    if (null == lockname)
                    {
                        currentSection = sec;
                    }
                    else
                    {
                        sec.locknamebytes = Encoding.UTF8.GetBytes(lockname);
                    }
                    return(sec);
                }
                else
                {
                    throw new Exception("CriticalSection.Create() handshake failed.");
                }
            }
            catch
            {
                if (ntsm != null)
                {
                    ntsm.Close();
                    ntsm = null;
                }
                sock.Close();
                sock = null;
                throw;
            }
        }
Beispiel #14
0
 private void CreatBluetoothClient()
 {
     if (mBluetoothStream != null)
     {
         mBluetoothStream.Close();
     }
     mobj_BluetootClinet.Close();
     mobj_BluetootClinet = new BluetoothClient();
 }
Beispiel #15
0
 public void Disconnect()
 {
     if (IsConnected)
     {
         _stream.Close();
         _client.Close();
         _stream = null;
         _client = null;
     }
 }
 public void close()
 {
     isOpen = false;
     if (ns != null)
     {
         ns.Close();
     }
     if (tcp != null)
     {
         tcp.Close();
     }
 }
Beispiel #17
0
 //切断ボタン
 private void button2_Click(object sender, EventArgs e)
 {
     if (ns != null)
     {
         //閉じる
         ns.Close();
         tcp.Close();
         label1.Text = "通信を切断しました。";
         socet       = false;
         //Console.ReadLine();
     }
 }
Beispiel #18
0
            internal static void Stop()
            {
                stop = true;

                if (hostToNetsms != null)
                {
                    lock (hostToNetsms)
                    {
                        foreach (KeyValuePair <string, System.Net.Sockets.NetworkStream> pair in hostToNetsms)
                        {
                            System.Net.Sockets.NetworkStream netsm = pair.Value;
                            try
                            {
                                netsm.WriteByte((byte)'s'); //Stop heartbeat
                            }
                            catch
                            {
                            }
                            finally
                            {
                                netsm.Close(1000);
                                netsm.Dispose();
                            }
                        }
                    }
                }

                if (receivethds != null)
                {
                    foreach (System.Threading.Thread thd in receivethds)
                    {
                        try
                        {
                            thd.Abort();
                        }
                        catch
                        {
                        }
                    }
                }

                if (monitorthd != null)
                {
                    try
                    {
                        monitorthd.Abort();
                    }
                    catch
                    {
                    }
                }
            }
Beispiel #19
0
        /******************************************************************************************
         * <summary>
         * POP Before SMTP認証のため、POPサーバに接続
         * <param name="strUser"></param>
         * <param name="strPass"></param>
         */
        public void             PopBeforeSmtp(String strUser, String strPass)
        {
            System.Net.Sockets.NetworkStream stream = null;
            System.Net.Sockets.TcpClient     tcp    = null;

            try{
                String strResult;

                tcp = new System.Net.Sockets.TcpClient();
                tcp.Connect(SERVER, PORT);
                stream = tcp.GetStream();

                strResult = WriteAndRead(stream, "");
                if (strResult.IndexOf("+OK") != 0)
                {
                    throw new Exception("Failed: POP Server Connection.");
                }

                strResult = WriteAndRead(stream, "USER " + strUser + "\r\n");
                if (strResult.IndexOf("+OK") != 0)
                {
                    throw new Exception("Error: User ID.");
                }

                strResult = WriteAndRead(stream, "PASS " + strPass + "\r\n");
                if (strResult.IndexOf("+OK") != 0)
                {
                    throw new Exception("Error: Pass");
                }

                strResult = WriteAndRead(stream, "STAT" + "\r\n");
                if (strResult.IndexOf("+OK") != 0)
                {
                }

                strResult = WriteAndRead(stream, "QUIT" + "\r\n");
            }
            catch (Exception e) {
                throw e;
            }
            finally{
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
                if (tcp != null)
                {
                    tcp.Close();
                }
            }
        }
 public void disconnection()
 {
     if (ns != null)
     {
         ns.Close();
     }
     //client.Close();
     if (listener != null)
     {
         listener.Stop();
     }
     connection = false;
 }
        public void FullyClose()
        {
            _connected = false;

            _tcpClient.Close();

            _chatWindow.Close();

            _stream.Close();

            _binaryReader.Close();

            _binaryWriter.Close();
        }
Beispiel #22
0
        //更新ボタン
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (socet && tcp.Available > 0) //通信ができていて、Serverから何か来てれば
            {
                //サーバーから送られたデータを受信する
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                byte[] resBytes           = new byte[256];
                int    resSize            = 0;
                do
                {
                    //データの一部を受信する
                    resSize = ns.Read(resBytes, 0, resBytes.Length);
                    //Readが0を返した時はサーバーが切断したと判断
                    if (resSize == 0)
                    {
                        statusBarText.Text = "サーバーが切断しました。";
                        break;
                    }
                    //受信したデータを蓄積する
                    ms.Write(resBytes, 0, resSize);
                    //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                    // 受信を続ける
                } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
                //受信したデータを文字列に変換
                System.Text.Encoding enc = System.Text.Encoding.UTF8;
                string resMsg            = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
                ms.Close();
                //末尾の\nを削除
                //resMsg = resMsg.TrimEnd('\n');
                //Console.WriteLine(resMsg);

                string[] stArrayData = resMsg.Split(','); //分割
                if (stArrayData.Length == 3)
                {
                    Normal_Text  = stArrayData[0];
                    ToLeft_Text  = stArrayData[1];
                    ToRight_Text = stArrayData[2];
                }

                if (ns != null)
                {
                    //閉じる
                    ns.Close();
                    tcp.Close();
                    statusBarText.Text = "通信を切断しました。";
                    socet = false;
                    //Console.ReadLine();
                }
            }
        }
Beispiel #23
0
        protected internal async void SendFile(string RemoteSeverName, int intFileSendPort, string sFullPathToFile) //Send file to _textBoxClientIpText():_numericUpDownClien()
        {
            client = new System.Net.Sockets.TcpClient(RemoteSeverName, intFileSendPort);
            try
            {
                using (System.IO.FileStream inputStream = System.IO.File.OpenRead(sFullPathToFile))
                {
                    using (System.Net.Sockets.NetworkStream outputStream = client.GetStream())
                    {
                        using (var cancellationTokenSource = new System.Threading.CancellationTokenSource(5000))
                        {
                            using (cancellationTokenSource.Token.Register(() => outputStream.Close()))
                            {
                                using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(outputStream))
                                {
                                    long   lenght     = inputStream.Length;
                                    long   totalBytes = 0;
                                    int    readBytes  = 0;
                                    byte[] buffer     = new byte[1024];
                                    try
                                    {
                                        writer.Write(System.IO.Path.GetFileName(sFullPathToFile));
                                        writer.Write(lenght);
                                        do
                                        {
                                            readBytes = await inputStream.ReadAsync(buffer, 0, buffer.Length);

                                            await outputStream.WriteAsync(buffer, 0, readBytes, cancellationTokenSource.Token);

                                            totalBytes += readBytes;
                                        } while (client.Connected && totalBytes < lenght);
                                    }
                                    catch (TimeoutException e)
                                    {
                                        readBytes = -1;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception expt)
            {
                Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + "Can't send file to " + RemoteSeverName + ": " + expt.Message);
            }
            client.Close();
        }
Beispiel #24
0
 public void Close()
 {
     if (null != netstm)
     {
         try
         {
             netstm.WriteByte((byte)'c');
             ensurenextplus();
         }
         catch
         {
         }
         netstm.Close();
         netstm = null;
     }
 }
Beispiel #25
0
        //切断ボタン
        private void button2_Click(object sender, EventArgs e)
        {
            if (socet == true)
            {
                //閉じる
                ns.Close();
                client.Close();
                Console.WriteLine("クライアントとの接続を閉じました。");

                //リスナを閉じる
                listener.Stop();
                Console.WriteLine("Listenerを閉じました。");

                label1.Text = "クライアントとの接続を閉じました。";
                socet       = false;
            }
            //Console.ReadLine();
        }
Beispiel #26
0
 /// <summary>
 /// 关闭网络流
 /// </summary>
 private void CloseNetworkStream()
 {
     if (_NetworkStream != null)
     {
         try
         {
             ClarifyInfo(string.Format("关闭连接到[{0}:{1}]的网络流……", m_RemoteHost, m_RemotePort), 1);
             _NetworkStream.Close();
         }
         catch (System.Exception ex)
         {
             ClarifyInfo(string.Format("关闭连接到[{0}:{1}]的网络流发生错误:{2}", m_RemoteHost, m_RemotePort, ex.Message), 0);
         }
         finally
         {
             _NetworkStream = null;
         }
     }
 }
Beispiel #27
0
        public void setup()
        {
            _client = new System.Net.Sockets.TcpClient();

            _client.Connect(_ip);
            _mainStream = _client.GetStream();

            writeString("handshake");
            if (readnWaitStream() == "ok")
            {
                writeString(_alias);
            }
            else
            {
                _mainStream.Close();
            }

            System.Threading.Thread t = new System.Threading.Thread(listener);
            t.Start();
        }
Beispiel #28
0
        public void Close()
        {
            try
            {
                if (netsm != null)
                {
                    netsm.Close();
                    netsm = null;
                }

                if (sock != null)
                {
                    sock.Close();
                    sock = null;
                }
            }
            catch
            {
            }
        }
Beispiel #29
0
 private void button2_Click(object sender, EventArgs e)
 {
     //close everything down before we leave.
     if (thisClient != null)
     {
         connected = false;
         try
         {
             networkStream.Close();
             thisClient.Close();
             networkStream.Dispose();
         }
         catch (Exception ex)
         {
             errDisp(ex);
         }
         lblStatus.Text      = "OFF-LINE";
         lblStatus.ForeColor = System.Drawing.Color.Red;
     }
     this.Close();
 }
Beispiel #30
0
        public void Connect(string address, int port)
        {
            _client = new System.Net.Sockets.TcpClient(address, port);
            _stream = _client.GetStream();
            Open?.Invoke();
            var messageSize = new byte[2];

            Task.Run(() =>
            {
                try
                {
                    while (IsConnected)
                    {
                        _stream.Read(messageSize, 0, 2);
                        var size    = BitConverter.ToUInt16(messageSize, 0);
                        var readSum = 0;
                        var buf     = new byte[size];
                        var message = new byte[0];
                        while (readSum < size)
                        {
                            var readSize = _stream.Read(buf, 0, size - readSum);
                            message      = message.Concat(buf.Take(readSize)).ToArray();
                            readSum     += readSize;
                        }

                        Received?.Invoke(message);
                    }
                }
                catch (Exception exception)
                {
                    OnError?.Invoke(exception);
                }

                _stream?.Close();
                _client?.Close();
                _stream = null;
                _client = null;
                Close?.Invoke();
            });
        }
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!disconnected)
                {
                    //クライアントにデータを送信する
                    //クライアントに送信する文字列を作成
                    string sendMsg = textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + "\r\n";
                    //文字列をByte型配列に変換
                    System.Text.Encoding enc = System.Text.Encoding.UTF8;
                    byte[] sendBytes         = enc.GetBytes(sendMsg + '\n');
                    //データを送信する
                    ns.Write(sendBytes, 0, sendBytes.Length);
                    //textBox1.Text += sendMsg;
                    //Console.WriteLine(sendMsg);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("接続されていません。", "エラー");
                State.Content += "―メッセージを送れませんでした―\r\n";
            }

            if (socet == true)
            {
                //閉じる
                ns.Close();
                client.Close();
                Console.WriteLine("クライアントとの接続を閉じました。");

                //リスナを閉じる
                listener.Stop();
                Console.WriteLine("Listenerを閉じました。");

                State.Content = "クライアントとの接続を閉じました。";
                socet         = false;
            }
        }
Beispiel #32
0
        /// <summary>
        /// 切断
        /// </summary>
        public void DisConnect()
        {
            if (ns != null)
            {
                try
                {
                    ns.Close();
                }
                catch { }
                ns = null;
            }
            if (objSck != null)
            {
                try
                {
                    objSck.Close();
                }
                catch { }
                objSck = null;
            }

            ConnectResult = false;
        }
Beispiel #33
0
        static void Main(string[] args)
        {           
            System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, 
                System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
            System.Net.Sockets.NetworkStream netstm = null;
            try
            {
                sock.Connect(System.Net.Dns.GetHostName(), 55901);
                netstm = new System.Net.Sockets.NetworkStream(sock);

                string str = XContent.ReceiveXString(netstm, null);
                string app = str;
                string sargs = "";
                int i = str.IndexOf(' ');
                if (i > -1)
                {
                    app = str.Substring(0, i);
                    sargs = str.Substring(i + 1);
                }

                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(app, sargs);
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                psi.StandardOutputEncoding = Encoding.UTF8;
                psi.RedirectStandardOutput = true;
                psi.RedirectStandardError = true;
                System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);

                netstm.WriteByte((byte)'+');

                string tname = System.Threading.Thread.CurrentThread.Name;

                System.Threading.Thread outthread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(stdoutputthreadproc));
                outthread.Name = "stdoutputthread_from" + tname;
                outthread.IsBackground = false;
                outthread.Start(new object[] { netstm, proc.StandardOutput, 'o' });

                System.Threading.Thread errthread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(stdoutputthreadproc));
                errthread.Name = "stderrorthread_from" + tname;
                errthread.IsBackground = true;
                errthread.Start(new object[] { netstm, proc.StandardError, 'e' });

                outthread.Join();
                errthread.Join();

                proc.WaitForExit();
                proc.Close();
            }
            catch (Exception e)
            {
                XLog.errorlog("DProcess error " + e.ToString());
            }
            finally
            {
                if(netstm != null)
                {
                    netstm.Close();
                    netstm = null;
                }
                sock.Close();
                sock = null;
            }
        }
Beispiel #34
0
        static void ClientThreadProc(object obj)
        {
            System.Net.Sockets.Socket dllclientSock = null;
            byte[] buf = new byte[0x400 * 4];
            try
            {
                dllclientSock = (System.Net.Sockets.Socket)obj;
                System.Net.Sockets.NetworkStream netstm = new System.Net.Sockets.NetworkStream(dllclientSock);
                for (bool run = true; run; )
                {
                    int ich = -1;
                    try
                    {
                        ich = netstm.ReadByte();
                    }
                    catch
                    {
                    }
                    if (ich == -1)
                    {
                        break;
                    }
                    switch (ich)
                    {
                        case 'p': // Pin shared memory.
                            {
                                try
                                {
                                    string smname = XContent.ReceiveXString(netstm, buf);

                                    IntPtr hf = INVALID_HANDLE_VALUE;
                                    IntPtr hmap = CreateFileMapping(hf, IntPtr.Zero, PAGE_READWRITE, 1, @"Global\" + smname);
                                    int lasterror = Marshal.GetLastWin32Error();
                                    if (IntPtr.Zero == hmap)
                                    {
                                        if (8 == lasterror)
                                        {
                                            throw new Exception("Shared memory segment named '" + smname + "' cannot be allocated; CreateFileMapping failed with ERROR_NOT_ENOUGH_MEMORY",
                                                new OutOfMemoryException());
                                        }
                                        throw new Exception("Shared memory segment named '" + smname + "' cannot be allocated; CreateFileMapping failed with GetLastWin32Error=" + lasterror);
                                    }
                                    if (ERROR_ALREADY_EXISTS != lasterror)
                                    {
                                        throw new Exception("Shared memory segment named '" + smname + "' not found");
                                    }
                                    IntPtr ipview = MapViewOfFile(hmap, FILE_MAP_ALL_ACCESS, 0, 0, 0);
                                    if (IntPtr.Zero == ipview)
                                    {
                                        lasterror = Marshal.GetLastWin32Error();
                                        CloseHandle(hmap);
                                        if (8 == lasterror)
                                        {
                                            throw new Exception("Shared memory segment named '" + smname + "' cannot be mapped into memory; MapViewOfFile failed with ERROR_NOT_ENOUGH_MEMORY",
                                                new OutOfMemoryException());
                                        }
                                        throw new Exception("Shared memory segment named '" + smname + "' cannot be mapped into memory; MapViewOfFile failed with GetLastWin32Error=" + lasterror);
                                    }

                                    PSM psm;
                                    psm.hmap = hmap;
                                    psm.ipview = ipview;
                                    psm.name = smname;
                                    lock (pins)
                                    {
                                        pins.Add(psm);
                                    }

                                    netstm.WriteByte((byte)'+');

                                }
                                catch(Exception e)
                                {
                                    try
                                    {
                                        netstm.WriteByte((byte)'-');
                                        XContent.SendXContent(netstm, e.ToString());
                                    }
                                    catch
                                    {
                                        throw new Exception("Unable to report exception to caller (pin shared memory)", e);
                                    }
                                }
                            }
                            break;

                        case 'u': // Unpin shared memory.
                            {
                                try
                                {
                                    string smname = XContent.ReceiveXString(netstm, buf);

                                    bool found = false;
                                    PSM psm = new PSM();
                                    lock (pins)
                                    {
                                        int ipsm = IndexOfPSM_unlocked(smname);
                                        if (-1 != ipsm)
                                        {
                                            psm = pins[ipsm];
                                            pins.RemoveAt(ipsm);
                                            found = true;
                                        }
                                    }
                                    if (found)
                                    {
                                        UnmapViewOfFile(psm.ipview);
                                        CloseHandle(psm.hmap);
                                        netstm.WriteByte((byte)'+');
                                    }
                                    else
                                    {
                                        netstm.WriteByte((byte)'-');
                                        XContent.SendXContent(netstm, "Cannot unpin; shared memory segment not pinned: " + smname);
                                    }

                                }
                                catch (Exception e)
                                {
                                    try
                                    {
                                        netstm.WriteByte((byte)'-');
                                        XContent.SendXContent(netstm, e.ToString());
                                    }
                                    catch
                                    {
                                        throw new Exception("Unable to report exception to caller (unpin shared memory)", e);
                                    }
                                }
                            }
                            break;

                        case 'c': // Close.
                            run = false;
                            break;
                    }
                }
                netstm.Close();
                dllclientSock.Close();
            }
            catch (Exception e)
            {
                XLog.errorlog("ClientThreadProc exception: " + e.ToString());

                try
                {
                    dllclientSock.Close();
                }
                catch (Exception e2)
                {
                }
            }
        }
Beispiel #35
0
        private void btnStartQuery_Click(object sender, EventArgs e)
        {
            btnStartQuery.Enabled = false;
            txtStatus.Text = "";
            lblThreadCount.Text = "0";
            startedThreadCount = 0;
            SetStatusStrip("Running tests...");

            string[] clients = SplitList(txtClients.Text);
            string[] hosts = SplitList(txtHosts.Text);
            testthds.Clear();           
            stopquery = false;
            bool isRoundRobin = radRobin.Checked;
            Random rnd = new Random();
            int nextdatasource = rnd.Next() % hosts.Length;

            for(int i = 0; i < clients.Length; i++)
            {
                string client = clients[i];
                string datasource = "";

                if (!isRoundRobin)
                {
                    datasource = txtHosts.Text.Trim();
                }
                else
                {
                    if (++nextdatasource > hosts.Length - 1)
                    {
                        nextdatasource = 0;
                    }
                    datasource = hosts[nextdatasource];
                }

                System.Threading.Thread thd = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()
                    {
                        if (string.Compare(client, "localhost", true) == 0)
                        {
                            client = System.Net.Dns.GetHostName();
                        }

                        System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                            System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
                        System.Net.Sockets.NetworkStream netstm = null;
                        try
                        {
                            sock.Connect(client, 55903);
                            netstm = new System.Net.Sockets.NetworkStream(sock);
                            netstm.WriteByte((byte)'s'); //Start test.
                            if (radNonquery.Checked)
                            {
                                netstm.WriteByte((byte)'n');
                            }
                            else
                            {
                                netstm.WriteByte((byte)'q');
                            }                            
                            XContent.SendXContent(netstm, txtSQL.Text.Trim());
                            string myconnstr = "Data Source = " + datasource;
                            {
                                string xcsoset = ConnStrOtherBox.Text.Trim();
                                if (0 != xcsoset.Length)
                                {
                                    myconnstr += "; " + xcsoset;
                                }
                            }
                            XContent.SendXContent(netstm, myconnstr);

                            if (netstm.ReadByte() != (byte)'+')
                            {
                                throw new Exception("Didn't receive success signal from protocol to start test for client: " + client);
                            }

                            lock (hosts)
                            {
                                startedThreadCount++;
                                SetControlPropertyValue(lblThreadCount, "Text", "Client Count: " + startedThreadCount.ToString());
                            }

                            while (!stopquery)
                            {
                                //Check to see if tests are still running.
                                netstm.WriteByte((byte)'p');
                                if (netstm.ReadByte() != '+')
                                {
                                    AppendStatusText(txtStatus, "Text", "Protocol didn't return a success signal.  Stopping test for client: " + client);
                                    break;
                                }
                                System.Threading.Thread.Sleep(3000);
                            }

                            netstm.WriteByte((byte)'t'); //stop test.

                            if (netstm.ReadByte() != (byte)'+')
                            {
                                throw new Exception("Didn't receive success signal from protocol to end test for client: " + client);
                            }
                        }
                        catch (Exception ex)
                        {
                            AppendStatusText(txtStatus, "Text", "Error while running test for client: " + client + ".  Error: " + ex.ToString());
                        }
                        finally
                        {
                            if (netstm != null)
                            {
                                netstm.Close();
                                netstm = null;
                            }
                            sock.Close();
                            sock = null;
                        } 
                    }));

                testthds.Add(thd);
                thd.Start();                
            }

            btnStopQuery.Enabled = true;
        }
Beispiel #36
0
        static void RunProxy(string sargs)
        {
            System.Net.Sockets.Socket lsock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
            System.Net.IPEndPoint ep = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 55901);

            try
            {
                for (int i = 0; ; i++)
                {
                    try
                    {
                        lsock.Bind(ep);
                        break;
                    }
                    catch
                    {
                        if (i >= 5)
                        {
                            throw;
                        }
                        System.Threading.Thread.Sleep(1000 * 4);
                        continue;
                    }
                }
                lsock.Listen(2);
                {
                    System.Net.Sockets.Socket ssock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                        System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
                    System.Net.Sockets.NetworkStream snetstm = null;
                    try
                    {
                        ssock.Connect(System.Net.Dns.GetHostName(), 55900);
                        snetstm = new System.Net.Sockets.NetworkStream(ssock);
                        snetstm.WriteByte((byte)'U');  //start DProcess
                        if (snetstm.ReadByte() != (byte)'+')
                        {
                            throw new Exception("Did not receive a success signal from service.");
                        }
                    }
                    finally
                    {
                        if (snetstm != null)
                        {
                            snetstm.Close();
                            snetstm = null;
                        }
                        ssock.Close();
                        ssock = null;
                    }
                }

                {
                    System.Net.Sockets.Socket csock = lsock.Accept();
                    System.Net.Sockets.NetworkStream cnetstm = null;
                    try
                    {
                        cnetstm = new System.Net.Sockets.NetworkStream(csock);
                        lsock.Close();
                        lsock = null;
                        XContent.SendXContent(cnetstm, sargs);
                        if (cnetstm.ReadByte() != (byte)'+')
                        {
                            throw new Exception("Did not receive a success signal from DProcess.");
                        }
                        StreamStdIO(cnetstm);
                    }
                    finally
                    {
                        if (cnetstm != null)
                        {
                            cnetstm.Close();
                            cnetstm = null;
                        }
                        csock.Close();
                        csock = null;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("RunProxy error: {0}", e.ToString());
            }
            finally
            {
                if (lsock != null)
                {
                    lsock.Close();
                    lsock = null;
                }
            }
        }
Beispiel #37
0
        /// <summary>
        /// Transmit message via TCP.
        /// </summary>
        /// <param name="message">Message to send via TCP.</param>
        /// <returns></returns>
        private bool TransmitMessage(NiawaNetMessage message)
        {
            bool succeeded = false;
            System.Net.Sockets.NetworkStream stream = null;

            /*
            //attempt lock
            bool tryLock = lockSection.WaitOne(60000);
            if (!tryLock) throw new TimeoutException("[" + _logInstanceName + "-T] Could not obtain lock while sending message");
            */

            try
            {
                //send message

                Byte[] messageBytes = message.ToByteArray();
                //set message length
                Byte[] messageLengthBytes = BitConverter.GetBytes((int)messageBytes.Length);
                //set message type
                Byte[] messageTypeBytes = BitConverter.GetBytes((int)NiawaNetMessage.MSG_TYPE_NIAWA_NET_MESSAGE);

                //get stream
                //stream = _netClient.GetStream();
                stream = new System.Net.Sockets.NetworkStream(_netClientSocket);

                //write len bytes
                stream.Write(messageLengthBytes, 0, 4);

                //write msg type bytes
                stream.Write(messageTypeBytes, 0, 4);

                //write msg data bytes
                stream.Write(messageBytes, 0, messageBytes.Length);

                stream.Flush();

                //messageInProgressGuid = string.Empty;
                succeeded = true;

                logger.Info("[" + _description + "-T] Message sent: Type [" + message.MessageType + "] SerialID [" + message.SerialID + "] Guid [" + message.Guid.ToString() + "]");
                //ipcLoggerMsg.Write("SentMessage", "[" + _logInstanceName + "]: " + message.MessageContents);
                _evtRaiser.RaiseEvent("Message", "Message Sent [" + message.SerialID + "]"
                    , Niawa.Utilities.InlineSortedListCreator.CreateStrStr("NiawaNetMessage", message.ToJson())
                    , _threadStatus.NodeID
                    , _threadStatus.ParentNodeID);
                _threadStatus.MessageCount += 1;

            }
            catch (Exception ex)
            {
                logger.Error("[" + _description + "-M] Error while transmitting message: " + ex.Message, ex);
                throw ex;
            }
            finally
            {
                if(stream!=null) stream.Close();

                /*
                //release lock
                lockSection.Release();
                */
            }

            return succeeded;
        }
Beispiel #38
0
            internal void ClientThreadProc(object _sock)
            {
                System.Net.Sockets.Socket clientsock = (System.Net.Sockets.Socket)_sock;
                netstm = new System.Net.Sockets.NetworkStream(clientsock);

                try
                {
                    for (bool stop = false; !stop; )
                    {
                        int ib;
                        try
                        {
                            ib = netstm.ReadByte();
                        }
                        catch(System.IO.IOException e)
                        {
                            if (e.InnerException is System.Net.Sockets.SocketException)
                            {
                                break;
                            }
                            throw;
                        }
                        if (ib < 0)
                        {
                            stop = true;
                            break;
                        }

                        switch (ib)
                        {
                            case 's': // Get DFS file size.
                                try
                                {
                                    string dfsfile = XContent.ReceiveXString(netstm, buf);
                                    string ssize = DirectDfs.GetFileSizeString(dfsfile);
                                    netstm.WriteByte((byte)'+');
                                    XContent.SendXContent(netstm, ssize);
                                }
                                catch (Exception e)
                                {
                                    netstm.WriteByte((byte)'-');
                                    XContent.SendXContent(netstm, e.ToString());
                                }
                                break;

                            case 'n': // Get DFS file part count.
                                try
                                {
                                    string dfsfile = XContent.ReceiveXString(netstm, buf);
                                    string spartcount = DirectDfs.GetFilePartCountString(dfsfile);
                                    netstm.WriteByte((byte)'+');
                                    XContent.SendXContent(netstm, spartcount);
                                }
                                catch (Exception e)
                                {
                                    netstm.WriteByte((byte)'-');
                                    XContent.SendXContent(netstm, e.ToString());
                                }
                                break;

                            case 'g': // Get DFS file contents.
                                try
                                {
                                    string dfsfile = XContent.ReceiveXString(netstm, buf);
                                    byte[] content = DirectDfs.GetFileContent(dfsfile);
                                    netstm.WriteByte((byte)'+');
                                    XContent.SendXContent(netstm, content);
                                }
                                catch (Exception e)
                                {
                                    netstm.WriteByte((byte)'-');
                                    XContent.SendXContent(netstm, e.ToString());
                                }
                                break;

                            case 'p': // Set DFS file contents; replaces if exists.
                                try
                                {
                                    string dfsfile = XContent.ReceiveXString(netstm, buf);
                                    string dfsfiletype = XContent.ReceiveXString(netstm, buf);
                                    buf = XContent.ReceiveXBytes(netstm, out buflen, buf);
                                    DirectDfs.SetFileContent(dfsfile, dfsfiletype, buf, buflen);
                                    netstm.WriteByte((byte)'+');
                                }
                                catch (Exception e)
                                {
                                    netstm.WriteByte((byte)'-');
                                    XContent.SendXContent(netstm, e.ToString());
                                }
                                break;

                            case 'd': // Delete DFS file.
                                try
                                {
                                    string dfsfile = XContent.ReceiveXString(netstm, buf);
                                    DirectDfs.DeleteFile(dfsfile);
                                    netstm.WriteByte((byte)'+');
                                }
                                catch (Exception e)
                                {
                                    netstm.WriteByte((byte)'-');
                                    XContent.SendXContent(netstm, e.ToString());
                                }
                                break;

                            case 'c': // Close.
                                stop = true;
                                netstm.WriteByte((byte)'+');
                                break;

                            case 199: // Handshake.
                                netstm.WriteByte(199 / 3);
                                break;

                            default:
                                throw new Exception("Unknown action: " + ((int)ib).ToString() + " char: " + (char)ib);
                        }
                    }
                }
                catch (Exception e)
                {
                    XLog.errorlog("DfsProtocolClientHandler.ClientThreadProc exception: " + e.ToString());
                }
                finally
                {
                    try
                    {
                        netstm.Close();
                        netstm = null;
                        clientsock.Close();
                        clientsock = null;
                    }
                    catch
                    {

                    }
                }
            }
Beispiel #39
0
        /** 別のプログラムと通信するための処理 */
        private void run()
        {
            //サーバーのホスト名とポート番号
            string host = "localhost";
            int port = 50001;

            //TcpClientを作成し、サーバーと接続する
            tcp = new System.Net.Sockets.TcpClient(host, port);

            //NetworkStreamを取得する
            ns = tcp.GetStream();
            Debug.Log("接続を開始します.");
            while (!terminate)
            {
                //受信したデータを文字列に変換
                string resMsg = "none";
                //サーバーから送られたデータを受信する
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                byte[] resBytes = new byte[256];
                do
                {
                    //データの一部を受信する
                    int resSize = ns.Read(resBytes, 0, resBytes.Length);
                    //Readが0を返した時はサーバーが切断したと判断
                    if (resSize == 0)
                    {
                        Debug.Log("サーバから切断されました.");
                        break;
                    }
                    //受信したデータを蓄積する
                    ms.Write(resBytes, 0, resSize);
                } while (ns.DataAvailable);
                //文字列をByte型配列に変換
                System.Text.Encoding enc = System.Text.Encoding.UTF8;
                resMsg = enc.GetString(ms.ToArray());
                ms.Close();
                lock (data)
                {
                    data = resMsg;
                }
                Debug.Log(data);
            }
            //閉じる
            ns.Close();
            tcp.Close();
            Debug.Log("Thread を終了します.");
        }
Beispiel #40
0
        static void ClientThreadProc(object obj)
        {
            System.Net.Sockets.Socket dllclientSock = null;
            byte[] buf = new byte[0x400 * 4];
            try
            {
                dllclientSock = (System.Net.Sockets.Socket)obj;
                System.Net.Sockets.NetworkStream netstm = new System.Net.Sockets.NetworkStream(dllclientSock);
                for (bool run = true; run; )
                {
                    int ich = -1;
                    try
                    {
                        ich = netstm.ReadByte();
                    }
                    catch
                    {
                    }
                    if (ich == -1)
                    {
                        break;
                    }
                    switch (ich)
                    {
                        case 'r': // Run!
                            {
                                Exception outputexception = null;
                                string output = "";
                                try
                                {
                                    string cmd = XContent.ReceiveXString(netstm, buf);
#if QEC2S_RUNTHREAD
                                    System.Threading.Thread thd = new System.Threading.Thread(
                                        new System.Threading.ThreadStart(
                                            delegate()
                                            {
#endif
                                                try
                                                {
                                                    output = Exec.Shell(cmd, false);
                                                }
                                                catch (Exception einner)
                                                {
                                                    outputexception = einner;
                                                }
#if QEC2S_RUNTHREAD
                                            }));
                                    thd.IsBackground = true;
                                    thd.Start();
                                    thd.Join();
#endif
                                    if (null == outputexception)
                                    {
                                        netstm.WriteByte((byte)'+');
                                        XContent.SendXContent(netstm, output);
                                    }
                                }
                                catch (Exception eouter)
                                {
                                    if (null == outputexception)
                                    {
                                        outputexception = eouter;
                                    }
                                }
                                if (null != outputexception)
                                {
                                    try
                                    {
                                        netstm.WriteByte((byte)'-');
                                        XContent.SendXContent(netstm, outputexception.ToString());
                                    }
                                    catch (Exception e)
                                    {
                                        XLog.errorlog("Error while reporting error: " + outputexception.ToString());
                                    }
                                }
                            }
                            break;

                        case 'c': // Close.
                            run = false;
                            break;
                    }
                }
                netstm.Close();
                dllclientSock.Close();
            }
            catch (Exception e)
            {
                XLog.errorlog("ClientThreadProc exception: " + e.ToString());

                try
                {
                    dllclientSock.Close();
                }
                catch (Exception e2)
                {
                }
            }
        }