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]; }
/// <summary> /// Open 通信要求受付(非同期) /// </summary> /// <param name="ipAddr">IPアドレス</param> /// <param name="ipPort">ポート</param> /// <returns></returns> public async void OpenAsync() { sw.Start(); //ListenするIPアドレス System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(listenIP); //TcpListenerオブジェクトを作成する listener = new System.Net.Sockets.TcpListener(ipAdd, listenPort); //Listenを開始する listener.Start(); Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); //接続要求があったら受け入れる //client = listener.AcceptTcpClient(); try { client = await listener.AcceptTcpClientAsync(); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port); //NetworkStreamを取得 ns = client.GetStream(); } catch (Exception) { } }
public bool Connect() { System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString); if (objSck != null) { objSck.Close(); objSck = null; } objSck = new System.Net.Sockets.TcpClient(); try { objSck.Connect(ipAdd, port); } catch(Exception) { return false; } //catch (Exception) //{ // throw; //} //NetworkStreamを取得 ns = objSck.GetStream(); return true; }
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; } }
public bool client_coneciton() { client = new System.Net.Sockets.TcpClient(IP_add, port); ns = client.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; return true; }
public MsgSource(int port) { this.port = port; Console.Write("Listening..."); server = System.Net.Sockets.TcpListener.Create(port); server.Start(); serverside_client = server.AcceptTcpClient(); Console.WriteLine("\nClient connected"); stream = serverside_client.GetStream(); }
public void open(ConnectionData cnn) { //TcpClientを作成し、サーバーと接続する tcp = new System.Net.Sockets.TcpClient(cnn.addr, cnn.port); //NetworkStreamを取得する ns = tcp.GetStream(); ns.WriteTimeout = 1; // isOpen = true; }
//通信開始ボタン(待機状態に) private void button1_Click(object sender, EventArgs e) { if (socet == false)//つながってないなら { try { //ListenするIPアドレス //string ipString = "127.0.0.1"; string ipString = textBox3.Text; System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); //ホスト名からIPアドレスを取得する時は、次のようにする //string host = "localhost"; //System.Net.IPAddress ipAdd = // System.Net.Dns.GetHostEntry(host).AddressList[0]; //.NET Framework 1.1以前では、以下のようにする //System.Net.IPAddress ipAdd = // System.Net.Dns.Resolve(host).AddressList[0]; //Listenするポート番号 int port = int.Parse(textBox4.Text); //TcpListenerオブジェクトを作成する listener = new System.Net.Sockets.TcpListener(ipAdd, port); //Listenを開始する listener.Start(); label1.Text = "Listenを開始しました(" + ((System.Net.IPEndPoint)listener.LocalEndpoint).Address + ":" + ((System.Net.IPEndPoint)listener.LocalEndpoint).Port + ")。"; //接続要求があったら受け入れる client = listener.AcceptTcpClient(); label1.Text = "クライアント(" + ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address + ":" + ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port + ")と接続しました。"; //NetworkStreamを取得 ns = client.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; socet = true; } catch (FormatException) { MessageBox.Show("IPアドレス、ポート番号を正しく入力してください(半角)", "エラー"); } catch (System.Net.Sockets.SocketException ER) { MessageBox.Show("IPアドレスが間違ってます。\ncmd.exeで調べてください\n(ipconfig)", "エラー"); } } }
public LSEncoder() { stdin = stdout = pstdin = pstdout = null; s = null; tc = null; enc = null; proc = null; pimp = null; dump = false; settings = null; crashed = false; locker = new object(); rekick = 0; }
public void DestroyConnection() { _continue = false; Close(); if (_networkStream != null) { _networkStream.Dispose(); _networkStream = null; } if (_client != null) { _client = null; } }
/**************************************************************************************************************/ /** <summary> Stop reading from the socket, and disconnect from the host </summary> */ public override void Close() { this.Abort(); if (this.socket != null) { this.stream = null; this.socket.Close(); this.socket = null; } return; }
public Terminal(Server s) { S = s; try { tc = new System.Net.Sockets.TcpClient(); tc.Connect(s.Address,s.Port); ns = tc.GetStream(); System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(Recv)); th.Start(); ChangeState(State.Connect); } catch { ChangeState(State.disConnect); } }
public void Initialize() { if (String.IsNullOrWhiteSpace(this.Hostname)) throw new Exception("Hostname must be set."); if (this.Port == default(Int16)) throw new Exception("Port must be set."); _client = new System.Net.Sockets.TcpClient(); _client.Connect(hostname: this.Hostname, port: this.Port); _networkStream = _client.GetStream(); _networkReader = new System.IO.BinaryReader(_networkStream); _networkStream.Write(Version, 0, Version.Length); ReceiveLoop(); }
public void Close() { if (null != netstm) { try { netstm.WriteByte((byte)'c'); ensurenextplus(); } catch { } netstm.Close(); netstm = null; } }
public void listen() { //System.Net.IPAddress ip = System.Net.IPAddress.Parse(IP_add); listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, port); System.Console.WriteLine("Port:{0}", port); listener.Start(); System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); System.Console.WriteLine("connect"); ns = client.GetStream(); ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; System.Console.WriteLine("connect2"); }
//接続ボタン private void button1_Click(object sender, EventArgs e) { try { //サーバーのIPアドレス(または、ホスト名)とポート番号 //string ipOrHost = "127.0.0.1"; //string ipOrHost = "127.0.0.1"; string ipOrHost = textBox3.Text; //string ipOrHost = "localhost"; //int port = 2001; int port = int.Parse(textBox4.Text); //TcpClientを作成し、サーバーと接続する tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); /* Console.WriteLine("サーバー({0}:{1})と接続しました({2}:{3})。", ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address, ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port); */ label1.Text = "サーバー(" + ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address + ":" + ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port + ")と接続しました(" + ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address + ":" + ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port + ")。"; //NetworkStreamを取得する ns = tcp.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; socet = true; } catch (FormatException)//入力がおかしい { MessageBox.Show("IPアドレス、ポート番号を正しく入力してください(半角)", "エラー"); } catch (System.Net.Sockets.SocketException)// { MessageBox.Show("Serverと接続できませんでした", "エラー"); } }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { try { Tuple<string, uint, string> req = (Tuple<string, uint, string>)e.Argument; for (uint i = 0; i < req.Item2; ++i) { if(e.Cancel) break; System.Net.Sockets.Socket s = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); s.Connect("localhost", 5124); System.Net.Sockets.NetworkStream ns = new System.Net.Sockets.NetworkStream(s); System.IO.StreamWriter sw = new System.IO.StreamWriter(ns); System.IO.StreamReader r = new System.IO.StreamReader(ns); sw.Write(req.Item1); sw.Flush(); backgroundWorker1.ReportProgress((int)((100 * i) / req.Item2), FormatResponse(r.ReadToEnd(), req.Item3)); } } catch (Exception ex) { e.Result = ex.ToString(); return; } }
/// <summary> /// クローズ /// </summary> public void Close() { //閉じる if (ns != null) { ns.Close(); ns = null; } if (client != null) { client.Close(); Console.WriteLine("クライアントとの接続を閉じました。"); client = null; } //リスナを閉じる if (null != listener) { listener.Stop(); Console.WriteLine("Listenerを閉じました。"); } }
/// <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; }
public void ReceiveDataAndEnqueue() { log.Context = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name; log.WriteLog("ReceiveData and Enqueue thread started..."); string s; int iCRat, iCRcount; string [] sa; int length = 0; string sLastErrorMessage = ""; while (!m_bDone) { try { try { m_NetworkStream = m_TCPClient.GetStream(); System.IAsyncResult asr = m_NetworkStream.BeginRead(m_bytesIncomingBuffer,m_iBufferLength,m_iBufferMaxLength - m_iBufferLength,null,null); while (!asr.IsCompleted && !m_bDone) { System.Threading.Thread.Sleep(100); } if (m_bDone) { continue; } //asr.AsyncWaitHandle.WaitOne(); length = m_NetworkStream.EndRead(asr); } catch (System.IO.IOException ioex) { if (null != ioex.InnerException) { if (ioex.InnerException is System.Net.Sockets.SocketException) { int iErrorCode = ((System.Net.Sockets.SocketException)ioex.InnerException).ErrorCode; string sErrorMessage = ((System.Net.Sockets.SocketException)ioex.InnerException).Message; sLastErrorMessage = "ReceiveDataAndEnqueue: Error Code = " + iErrorCode.ToString() + " Description = " + sErrorMessage; } else { sLastErrorMessage = "ReceiveDataAndEnqueue: Unknown Error detected. Description = " + ioex.Message; } log.WriteLog(sLastErrorMessage); } m_bDone = true; m_bConnected = false; } catch (System.Exception ex) { sLastErrorMessage = "ReceiveDataAndEnqueue: Unknown Error detected. Description = " + ex.Message; log.WriteLog(sLastErrorMessage); m_bDone = true; m_bConnected = false; } if(!m_bConnected) { OnConnectionErrorReceived(this,sLastErrorMessage); continue; } if (m_bDone) continue; if (0 == length) { // connection must have been reset m_bDone = true; m_bConnected = false; continue; } m_iBufferLength += length; // find all the messages in the stream iCRcount = 0; for (int i = 0; i < m_iBufferLength; i++) { if (m_bytesIncomingBuffer[i] == 13) iCRcount++; } // for // post all messages from the stream for (int i = 0; i < iCRcount; i++) { s = System.Text.Encoding.ASCII.GetString(m_bytesIncomingBuffer); s = s.Substring(0,m_iBufferLength); iCRat = s.IndexOf((char)13); if (-1 != iCRat) { int iLen; s = s.Substring(0,iCRat); iLen = s.Length + 1; m_iBufferLength -= iLen; m_sLastResponse = s; lock (m_qCommands.SyncRoot) { CarverLab.Oyster.Encoder.Command cmd; string [] saParams; sa = CarverLab.Oyster.Encoder.Command.DecodeCommand(System.Text.Encoding.ASCII.GetBytes(s),s.Length); if (sa.Length > 1) { saParams = new string[sa.Length - 1]; Array.Copy(sa,1,saParams,0,sa.Length - 1); cmd = new CarverLab.Oyster.Encoder.Command(sa[0],saParams); } else { cmd = new CarverLab.Oyster.Encoder.Command(sa[0],null); } m_qCommands.Enqueue(cmd); } byte [] bytes = new byte[m_iBufferLength]; Array.Copy(m_bytesIncomingBuffer,0,bytes,0,m_iBufferLength); CarverLab.Oyster.Encoder.CommandEventArgs cea = new CarverLab.Oyster.Encoder.CommandEventArgs(bytes, ref m_qCommands); OnMessageReceived(cea); m_EventMessageAvailable.Set(); Array.Copy(m_bytesIncomingBuffer,iLen,m_bytesIncomingBuffer,0,m_iBufferLength); Array.Clear(m_bytesIncomingBuffer,m_iBufferLength,m_iBufferMaxLength - m_iBufferLength); } // if } // for } catch (System.Exception ex) { log.WriteLog("Exception: " + ex.Message); } } // while m_EventThreadComplete.Set(); }
/// <summary> /// Connect to wm irc /// </summary> public static void Connect() { if (!terminated) { try { Random rand = new Random(); int random_number = rand.Next(10000); nick = "wm-bot" + System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace("\\", "").Replace(".", "").Replace(" ", "") + random_number.ToString(); core.Log("Connecting to wikimedia recent changes feed as " + nick + ", hold on"); stream = new System.Net.Sockets.TcpClient("irc.wikimedia.org", 6667).GetStream(); WD = new StreamWriter(stream); RD = new StreamReader(stream, System.Text.Encoding.UTF8); Thread pinger = new Thread(Pong); Send("USER " + "wm-bot" + " 8 * :" + "wm-bot"); Send("NICK " + nick); WD.Flush(); pinger.Start(); foreach (string b in channels) { System.Threading.Thread.Sleep(800); Send("JOIN " + b); WD.Flush(); } core.Log("Connected to feed - OK"); Loaded = true; } catch (Exception fail) { core.handleException(fail, "RC"); } } }
public static DateTime GetNetDateTime() { //返回国际标准时间 //只使用的TimerServer的IP地址,未使用域名 string[,] TimerServer = new string[14, 2]; int[] ServerTab = new int[] { 3, 2, 4, 8, 9, 6, 11, 5, 10, 0, 1, 7, 12 }; TimerServer[0, 0] = "time-a.nist.gov"; TimerServer[0, 1] = "129.6.15.28"; TimerServer[1, 0] = "time-b.nist.gov"; TimerServer[1, 1] = "129.6.15.29"; TimerServer[2, 0] = "time-a.timefreq.bldrdoc.gov"; TimerServer[2, 1] = "132.163.4.101"; TimerServer[3, 0] = "time-b.timefreq.bldrdoc.gov"; TimerServer[3, 1] = "132.163.4.102"; TimerServer[4, 0] = "time-c.timefreq.bldrdoc.gov"; TimerServer[4, 1] = "132.163.4.103"; TimerServer[5, 0] = "utcnist.colorado.edu"; TimerServer[5, 1] = "128.138.140.44"; TimerServer[6, 0] = "time.nist.gov"; TimerServer[6, 1] = "192.43.244.18"; TimerServer[7, 0] = "time-nw.nist.gov"; TimerServer[7, 1] = "131.107.1.10"; TimerServer[8, 0] = "nist1.symmetricom.com"; TimerServer[8, 1] = "69.25.96.13"; TimerServer[9, 0] = "nist1-dc.glassey.com"; TimerServer[9, 1] = "216.200.93.8"; TimerServer[10, 0] = "nist1-ny.glassey.com"; TimerServer[10, 1] = "208.184.49.9"; TimerServer[11, 0] = "nist1-sj.glassey.com"; TimerServer[11, 1] = "207.126.98.204"; TimerServer[12, 0] = "nist1.aol-ca.truetime.com"; TimerServer[12, 1] = "207.200.81.113"; TimerServer[13, 0] = "nist1.aol-va.truetime.com"; TimerServer[13, 1] = "64.236.96.53"; int portNum = 13; string hostName; byte[] bytes = new byte[1024]; int bytesRead = 0; System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); for (int i = 0; i < 13; i++) { hostName = TimerServer[ServerTab[i], 0]; try { client.Connect(hostName, portNum); System.Net.Sockets.NetworkStream ns = client.GetStream(); bytesRead = ns.Read(bytes, 0, bytes.Length); client.Close(); break; } catch (System.Exception) { return(new DateTime(0)); } } char[] sp = new char[1]; sp[0] = ' '; System.DateTime dt = new DateTime(); string str1; str1 = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRead); string[] s; s = str1.Split(sp); dt = System.DateTime.Parse(s[1] + " " + s[2]);//得到标准时间 //dt=dt.AddHours (8);//得到北京时间*/ return(dt); }
/// <summary> /// 接收 /// </summary> /// <param name="tcpClient"></param> /// <param name="encoding">默认UTF8</param> /// <returns></returns> public static string Receive(System.Net.Sockets.TcpClient tcpClient, System.Text.Encoding encoding = null) { string r = string.Empty; using (System.IO.MemoryStream msContent = new System.IO.MemoryStream()) { int totalBytesRead = 0; // 读取总长度 -- 用于累积超出 s_BufferSize 时 int startCharIndex = -1; int endCharIndex = -1; byte[] buffOfNetworkStream = new byte[s_BufferSize]; int lastestBytesRead = 0; // 当前读取总长度 System.Net.Sockets.NetworkStream networkStream = tcpClient.GetStream(); lastestBytesRead = networkStream.Read(buffOfNetworkStream, 0, s_BufferSize); totalBytesRead = totalBytesRead + lastestBytesRead; // 定位 StartChar for (int i = 0; i < buffOfNetworkStream.Length; i++) { if (s_StartChar == Convert.ToChar(buffOfNetworkStream[i])) { startCharIndex = i; break; } } if (startCharIndex < 0) { throw new Exception("缺少(Char)Start"); } // 获取内容长度 ( int类型, 共 4 个字节 ) int contentLength = BitConverter.ToInt32(buffOfNetworkStream, startCharIndex + 1); // 内容长度 // 首次获取写入内容 msContent.Write ( buffOfNetworkStream, startCharIndex + 1 + 4, // (Char)Start 起始位置 + 1( (char)Start 1 个字节 ) + 4( 内容长度 4 个字节 ) lastestBytesRead - (startCharIndex + 1 + 4) ); while (totalBytesRead < 1 + 4 + contentLength + 1) // 1( (char)Start 1 个字节 ) + 4( 内容长度 4 个字节 ) + contentLength ( 读取出来的长度信息 ) + 1( (char)End 1 个字节 ) { lastestBytesRead = networkStream.Read(buffOfNetworkStream, 0, Util.Web.TcpClientUtils.s_BufferSize); // 再次获取剩余的内容 totalBytesRead = totalBytesRead + lastestBytesRead; msContent.Write(buffOfNetworkStream, 0, lastestBytesRead); } byte[] contentByteArr = msContent.GetBuffer(); if (encoding != null) { r = encoding.GetString(contentByteArr, 0, contentByteArr.Length); } else { r = Encoding.UTF8.GetString(contentByteArr, 0, contentByteArr.Length); } // 定位 EndChar endCharIndex = r.IndexOf(s_EndChar); if (endCharIndex < 0) { throw new Exception("缺少(Char)End"); } r = r.Substring(0, endCharIndex); // 释放 networkStream = null; return(r); } }
/// <include file='InterfaceDocumentationComments.xml' path='doc/members/member[@name="M:OperatingSystemAbstraction.ITcpClient.GetStream"]/*'/> public INetworkStream GetStream() { // Returning System.Net.Sockets.NetworkStream wrapped in an OperatingSystemAbstraction.NetworkStream (which implements INetworkStream), allows this method to be mocked System.Net.Sockets.NetworkStream networkStream = tcpClient.GetStream(); return(new NetworkStream(networkStream)); }
static void Main(string[] args) { System.Net.IPAddress l_ip = System.Net.IPAddress.Parse("127.0.0.1"); int l_port = 2001; System.Net.Sockets.TcpListener l_listener = new System.Net.Sockets.TcpListener(l_ip, l_port); l_listener.Start(); Console.WriteLine("Listenを開始しました({0} : {1})", ((System.Net.IPEndPoint)l_listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)l_listener.LocalEndpoint).Port); System.Net.Sockets.TcpClient l_client = l_listener.AcceptTcpClient(); Console.WriteLine("client({0} : {1})と接続しました", ((System.Net.IPEndPoint)l_client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)l_client.Client.RemoteEndPoint).Port); System.Net.Sockets.NetworkStream l_ns = l_client.GetStream(); l_ns.ReadTimeout = 10000; l_ns.WriteTimeout = 10000; System.Text.Encoding l_enc = System.Text.Encoding.UTF8; bool l_disconnected = false; System.IO.MemoryStream l_ms = new System.IO.MemoryStream(); byte[] l_resBytes = new byte[256]; int l_resSize = 0; do { l_resSize = l_ns.Read(l_resBytes, 0, l_resBytes.Length); if (l_resSize == 0) { l_disconnected = true; Console.WriteLine("clientが切断しました"); break; } l_ms.Write(l_resBytes, 0, l_resSize); } while (l_ns.DataAvailable || l_resBytes[l_resSize - 1] != '\n'); string l_resMsg = l_enc.GetString(l_ms.GetBuffer(), 0, (int)l_ms.Length); l_ms.Close(); l_resMsg = l_resMsg.TrimEnd('\n'); Console.WriteLine(l_resMsg); if (!l_disconnected) { string l_sendMsg = l_resMsg.Length.ToString(); byte[] l_sendBytes = l_enc.GetBytes(l_sendMsg + '\n'); Console.WriteLine(l_sendMsg); } l_ns.Close(); l_client.Close(); Console.WriteLine("clientとの接続を閉じました"); l_listener.Stop(); Console.WriteLine("Listenerを閉じました。"); Console.ReadLine(); }
static void Main(string[] args) { String[] src = File.ReadAllLines(@"C:\Users\ymine\skkdic\SKK-JISYO.L", Encoding.GetEncoding("EUC-JP")); if (src == null) { System.Environment.Exit(0); } List <String> dic = new List <string>(src); dic.Sort(); List <String> midasi = new List <string>(); foreach (String item in dic) { midasi.Add(item.Split(' ')[0]); } //ListenするIPアドレス string ipString = "127.0.0.1"; System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); //ホスト名からIPアドレスを取得する時は、次のようにする //string host = "localhost"; //System.Net.IPAddress ipAdd = // System.Net.Dns.GetHostEntry(host).AddressList[0]; //.NET Framework 1.1以前では、以下のようにする //System.Net.IPAddress ipAdd = // System.Net.Dns.Resolve(host).AddressList[0]; //Listenするポート番号 int port = 2001; //TcpListenerオブジェクトを作成する System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAdd, port); //Listenを開始する listener.Start(); Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); //接続要求があったら受け入れる System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("クライアント({0}:{1})と接続しました。", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port); //NetworkStreamを取得 System.Net.Sockets.NetworkStream ns = client.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) // ns.ReadTimeout = 10000; // ns.WriteTimeout = 10000; //クライアントから送られたデータを受信する System.Text.Encoding enc = System.Text.Encoding.UTF8; bool disconnected = false; System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; /** * while ((resSize = ns.Read(resBytes, 0, resBytes.Length)) != 0) * { * ms.Write(resBytes, 0, resSize); * } * */ do { //データの一部を受信する resSize = ns.Read(resBytes, 0, resBytes.Length); //Readが0を返した時はクライアントが切断したと判断 if (resSize == 0) { disconnected = true; Console.WriteLine("クライアントが切断しました。"); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); //まだ読み取れるデータがあるか、データの最後が\nでない時は、 // 受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); //受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); // resMsg = resMsg.TrimEnd('\r'); Console.WriteLine(resMsg); int index = midasi.BinarySearch(resMsg); String sendMsg = String.Empty; if (index > -1) { sendMsg = dic[index].Split(' ')[1]; } else { sendMsg = "Not found..."; } //クライアントにデータを送信する //クライアントに送信する文字列を作成 //文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); //閉じる ns.Close(); client.Close(); Console.WriteLine("クライアントとの接続を閉じました。"); //リスナを閉じる listener.Stop(); Console.WriteLine("Listenerを閉じました。"); Console.ReadLine(); }
private void httpReqGetOptions(string request, System.Net.Sockets.NetworkStream networkStream, out bool stream) { stream = false; }
static void Main(string[] args) { const int PORT = 8810; if (args.Length == 1) { uint msgId = 0; string dir = args[0]; System.Net.Sockets.TcpListener server = null; try { System.Net.IPEndPoint localAddress = new System.Net.IPEndPoint(0, PORT); server = new System.Net.Sockets.TcpListener(localAddress); server.Start(); System.Console.WriteLine("파일 다운로드 대기 중..."); while (true) { System.Net.Sockets.TcpClient client = server.AcceptTcpClient(); System.Console.WriteLine("{0} 연결", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).ToString()); System.Net.Sockets.NetworkStream stream = client.GetStream(); FUP.Message reqMsg = FUP.MessageUtil.Receive(stream); if (reqMsg.Header.MSGTYPE != FUP.CONSTANTS.REQ_FILE_SEND) { stream.Close(); client.Close(); continue; } FUP.BodyRequest reqBody = (FUP.BodyRequest)reqMsg.Body; System.Console.WriteLine("파일 전송 요청이 왔습니다. 수락하시겠습니까? (yes/no)"); string answer = System.Console.ReadLine(); FUP.Message rspMsg = new FUP.Message(); rspMsg.Body = new FUP.BodyResponse() { MSGID = reqMsg.Header.MSGID, RESPONSE = FUP.CONSTANTS.ACCEPTED }; rspMsg.Header = new FUP.Header() { MSGID = msgId++, MSGTYPE = FUP.CONSTANTS.REP_FILE_SEND, BODYLEN = (uint)rspMsg.Body.GetSize(), FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED, LASTMSG = FUP.CONSTANTS.LASTMSG, SEQ = 0 }; if (answer != "yes" && answer != "y") { rspMsg.Body = new FUP.BodyResponse() { MSGID = reqMsg.Header.MSGID, RESPONSE = FUP.CONSTANTS.DENIED }; FUP.MessageUtil.Send(stream, rspMsg); stream.Close(); client.Close(); continue; } else { FUP.MessageUtil.Send(stream, rspMsg); } System.Console.WriteLine("파일 전송을 시작합니다."); if (System.IO.Directory.Exists(dir) == false) { System.IO.Directory.CreateDirectory(dir); } long fileSize = reqBody.FILESIZE; string fileName = System.Text.Encoding.Default.GetString(reqBody.FILENAME); System.IO.FileStream file = new System.IO.FileStream(dir + "\\" + fileName, System.IO.FileMode.Create); uint? dataMsgId = null; ushort prevSeq = 0; while ((reqMsg = FUP.MessageUtil.Receive(stream)) != null) { System.Console.Write("#"); if (reqMsg.Header.MSGTYPE != FUP.CONSTANTS.FILE_SEND_DATA) { break; } if (dataMsgId == null) { dataMsgId = reqMsg.Header.MSGID; } else { if (dataMsgId != reqMsg.Header.MSGID) { break; } } if (prevSeq++ != reqMsg.Header.SEQ) { System.Console.WriteLine("{0}, {1}", prevSeq, reqMsg.Header.SEQ); break; } file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize()); if (reqMsg.Header.FRAGMENTED == FUP.CONSTANTS.NOT_FRAGMENTED) { break; } if (reqMsg.Header.LASTMSG == FUP.CONSTANTS.LASTMSG) { break; } } long recvFileSize = file.Length; file.Close(); System.Console.WriteLine(); System.Console.WriteLine("수신 파일 크기 : {0}byte", recvFileSize); FUP.Message rstMsg = new FUP.Message(); rstMsg.Body = new FUP.BodyResult() { MSGID = reqMsg.Header.MSGID, RESULT = FUP.CONSTANTS.SUCCESS }; rstMsg.Header = new FUP.Header() { MSGID = msgId++, MSGTYPE = FUP.CONSTANTS.FILE_SEND_RES, BODYLEN = (uint)rstMsg.Body.GetSize(), FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED, LASTMSG = FUP.CONSTANTS.LASTMSG, SEQ = 0 }; if (fileSize == recvFileSize) { FUP.MessageUtil.Send(stream, rstMsg); } else { rstMsg.Body = new FUP.BodyResult() { MSGID = reqMsg.Header.MSGID, RESULT = FUP.CONSTANTS.FAIL }; FUP.MessageUtil.Send(stream, rstMsg); } System.Console.WriteLine("파일 전송을 마쳤습니다."); stream.Close(); client.Close(); } } catch (System.Net.Sockets.SocketException e) { System.Console.WriteLine(e); } finally { server.Stop(); } } else if (args.Length == 2) { const int CHUNK_SIZE = 4096; string serverIp = args[0]; string filepath = args[1]; try { System.Net.IPEndPoint clientAddress = new System.Net.IPEndPoint(0, 0); System.Net.IPEndPoint serverAddress = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(serverIp), PORT); System.IO.FileInfo fileinfo = new System.IO.FileInfo(filepath); System.Console.WriteLine("클라이언트: {0}, 서버: {0}", clientAddress.ToString(), serverAddress.ToString()); uint msgId = 0; FUP.Message reqMsg = new FUP.Message(); reqMsg.Body = new FUP.BodyRequest() { FILESIZE = fileinfo.Length, FILENAME = System.Text.Encoding.Default.GetBytes(fileinfo.Name) }; reqMsg.Header = new FUP.Header() { MSGID = msgId++, MSGTYPE = FUP.CONSTANTS.REQ_FILE_SEND, BODYLEN = (uint)reqMsg.Body.GetSize(), FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED, LASTMSG = FUP.CONSTANTS.LASTMSG, SEQ = 0 }; System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(clientAddress); client.Connect(serverAddress); System.Net.Sockets.NetworkStream stream = client.GetStream(); FUP.MessageUtil.Send(stream, reqMsg); FUP.Message rspMsg = FUP.MessageUtil.Receive(stream); if (rspMsg.Header.MSGTYPE != FUP.CONSTANTS.REP_FILE_SEND) { System.Console.WriteLine("정상적인 서버 응답이 아닙니다. {0}", rspMsg.Header.MSGTYPE); return; } if (((FUP.BodyResponse)rspMsg.Body).RESPONSE == FUP.CONSTANTS.DENIED) { System.Console.WriteLine("서버에서 파일 전송을 거부했습니다."); return; } using (System.IO.Stream fileStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open)) { byte[] rbytes = new byte[CHUNK_SIZE]; long readValue = System.BitConverter.ToInt64(rbytes, 0); int totalRead = 0; ushort msgSeq = 0; byte fragmented = (fileStream.Length < CHUNK_SIZE) ? FUP.CONSTANTS.NOT_FRAGMENTED : FUP.CONSTANTS.FRAGMENTED; while (totalRead < fileStream.Length) { int read = fileStream.Read(rbytes, 0, CHUNK_SIZE); totalRead += read; FUP.Message fileMsg = new FUP.Message(); byte[] sendBytes = new byte[read]; System.Array.Copy(rbytes, 0, sendBytes, 0, read); fileMsg.Body = new FUP.BodyData(sendBytes); fileMsg.Header = new FUP.Header() { MSGID = msgId, MSGTYPE = FUP.CONSTANTS.FILE_SEND_DATA, BODYLEN = (uint)fileMsg.Body.GetSize(), FRAGMENTED = fragmented, LASTMSG = (totalRead < fileStream.Length) ? FUP.CONSTANTS.NOT_LASTMSG : FUP.CONSTANTS.LASTMSG, SEQ = msgSeq++ }; System.Console.Write("#"); FUP.MessageUtil.Send(stream, fileMsg); } System.Console.WriteLine(); FUP.Message rstMsg = FUP.MessageUtil.Receive(stream); FUP.BodyResult result = (FUP.BodyResult)rstMsg.Body; System.Console.WriteLine("파일 전송을 마쳤습니다."); } stream.Close(); client.Close(); } catch (System.Net.Sockets.SocketException e) { System.Console.WriteLine(e); } } else { System.Console.WriteLine("파일 받는 법:\t{0} \"다운로드 경로\"", System.Diagnostics.Process.GetCurrentProcess().ProcessName); System.Console.WriteLine("파일 보내는 법:\t{0} \"보낼 IP\" \"업로드할 파일\"", System.Diagnostics.Process.GetCurrentProcess().ProcessName); } return; }
public static int socketCom() { //ListenするIPの指定 string IP_String = "0.0.0.0"; System.Net.IPAddress IP_Address = System.Net.IPAddress.Parse(IP_String); //Listenするport番号 int PORT = 5000; //TcpListenerオブジェクトの作成 System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(IP_Address, PORT); //Listenを開始 listener.Start(); // Console.WriteLine("Listenを開始しました({0}:{1})", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,((System.Net.IPEndPoint)listener.LocalEndpoint).Port); //接続要求のチェック,受け入れ System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); /* Console.WriteLine("クライアント({0}:{1})と接続しました。", * ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address, * ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port); */ //NetworkStreamを取得 System.Net.Sockets.NetworkStream ns = client.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; //クライアントから送られたデータを受信する System.Text.Encoding enc = System.Text.Encoding.UTF8; bool disconnected = false; System.IO.MemoryStream ms = new System.IO.MemoryStream(); byte[] resBytes = new byte[256]; int resSize = 0; StreamReader sr = new StreamReader(ns, enc); string resMsg = String.Empty; string[] values = new string[3]; do { resMsg = sr.ReadLine(); if (resMsg == null) { break; } Console.WriteLine(resMsg); values = resMsg.Split(' '); switch (values[0]) { case "theta:": thetaFromAndroid = double.Parse(values[1]); break; case "dist:": distFromAndroid = double.Parse(values[1]); break; case "lean:": break; default: break; } } while (true); //受信したデータを文字列に変換 resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); //閉じる ms.Close(); ns.Close(); client.Close(); // Console.WriteLine("クライアントとの接続を閉じました。"); //リスナを閉じる listener.Stop(); // Console.WriteLine("Listenerを閉じました。"); Console.ReadLine(); return(1); //規定文字が来たら,-1などを返すようにあとで変える }
/// <summary> /// 受信コマンド解析 /// </summary> /// <returns></returns> public string TCP_ReciveCommand() { if (null == objTCPSC) { return(""); } System.Net.Sockets.TcpClient objSck = objTCPSC.SckProperty; System.Net.Sockets.NetworkStream objStm = objTCPSC.MyProperty; string readStr = ""; if (objStm != null && objSck != null) { // ソケット受信 if (objSck.Available > 0 && objStm.DataAvailable) { Byte[] dat = new Byte[objSck.Available]; if (0 == objStm.Read(dat, 0, dat.GetLength(0))) { // 切断を検知 objTCPSC.Dispose(); return(""); } readStr = System.Text.Encoding.GetEncoding("SHIFT-JIS").GetString(dat); hwResiveStr += readStr; { string[] rsvCmd = readStr.Split('$'); for (int i = 0; i < rsvCmd.Length; i++) { if (rsvCmd[i].Length <= 3) { continue; } // ロータリーエンコーダから 速度を計算 if (rsvCmd[i].Substring(0, 3) == "A1,") { const double tiyeSize = 140.0; // タイヤ直径 [mm] const double OnePuls = 250.0; // 一周のパルス数 double ResiveMS; double ResReR, ResReL; string[] splStr = rsvCmd[i].Split(','); // 0 A1 double.TryParse(splStr[1], out ResiveMS); // 小数点付き 秒 double.TryParse(splStr[2], out ResReR); // Right Wheel double.TryParse(splStr[3], out ResReL); // Left Wheel // 0.5秒以上の経過時間があれば計算 (あまりに瞬間的な値では把握しにくいため) if ((ResiveMS - oldResiveMS) > 0.5) { // 速度計算(非動輪を基準) SpeedMH = (int)(((double)(hwRErotR - oldWheelR) / OnePuls * (Math.PI * tiyeSize)) / (ResiveMS - oldResiveMS)); oldResiveMS = ResiveMS; oldWheelR = hwRErotR; } // 初回のパルス値リセット if (bInitRePulse) { ReInitR = ResReR; ReInitL = ResReL; bInitRePulse = false; } // 初回からの変化値 hwRErotR = ResReR - ReInitR; hwRErotL = ResReL - ReInitL; bhwRE = true; } else if (rsvCmd[i].Substring(0, 3) == "A2,") { // コンパス情報 // A2,22.5068,210$ double ResiveMS; int ResiveCmp; string[] splStr = rsvCmd[i].Split(','); // splStr[0] "A2" // ミリ秒取得 double.TryParse(splStr[1], out ResiveMS); // ms? 万ミリ秒に思える int.TryParse(splStr[2], out ResiveCmp); // デジタルコンパス値 hwCompass = ResiveCmp; bhwCompass = true; } else if (rsvCmd[i].Substring(0, 3) == "A3,") { // GPS情報 // $A3,38.266,36.8002,140.11559$ double ResiveMS; double ResiveLandX; // 緯度 double ResiveLandY; // 経度 string[] splStr = rsvCmd[i].Split(','); // データが足らないことがある if (splStr.Length >= 4) { // splStr[0] "A3" // ミリ秒取得 double.TryParse(splStr[1], out ResiveMS); // ms? 万ミリ秒に思える double.TryParse(splStr[2], out ResiveLandX); // GPS値 double.TryParse(splStr[3], out ResiveLandY); hwGPS_LandX = ResiveLandX; hwGPS_LandY = ResiveLandY; bhwGPS = true; bhwUsbGPS = false; } } else if (rsvCmd[i].Substring(0, 3) == "A4,") { // ロータリーエンコーダ プロット座標 // 開始時 真北基準 /* * コマンド * A4 * ↓ * 戻り値 * A4,絶対座標X,絶対座標Y,絶対座標上での向きR$ * * 絶対座標X[mm] * 絶対座標Y[mm] * 絶対座標上での向き[rad] -2π~2π * 浮動小数点です。 */ double ResiveMS; double ResiveX; double ResiveY; double ResiveRad; string[] splStr = rsvCmd[i].Split(','); // splStr[0] "A4" // ミリ秒取得 double.TryParse(splStr[1], out ResiveMS); // ms? 万ミリ秒に思える double.TryParse(splStr[2], out ResiveX); // 絶対座標X mm double.TryParse(splStr[3], out ResiveY); // 絶対座標Y mm double.TryParse(splStr[4], out ResiveRad); // 向き -2PI 2PI // 座標系変換 // 右上から右下へ #if true // 座標軸を変換 ResiveY = -ResiveY; //ResiveRad = -ResiveRad; // リセットした時点での電子コンパスの向きを元にマップ座標へ変換する // x*cos - y*sin // x*sin + y*cos { hwREDir = ((-ResiveRad * 180.0) / Math.PI) + hwREStartDir; double theta = hwREStartDir / 180.0 * Math.PI; hwREX = (ResiveX * Math.Cos(theta) - ResiveY * Math.Sin(theta)) + hwREStartX; hwREY = (ResiveX * Math.Sin(theta) + ResiveY * Math.Cos(theta)) + hwREStartY; } #else hwREDir = ((-ResiveRad * 180.0) / Math.PI); hwREX = ResiveX; hwREY = ResiveY; #endif bhwREPlot = true; } } } } } return(readStr); }
public bool Open() { RLib.WatchLog.Loger.Log("打开连接..." + Thread.CurrentThread.ManagedThreadId, ""); Console.WriteLine("打开连接..."); try { RLib.WatchLog.Loger.Log("正在打开tcp..." + Thread.CurrentThread.ManagedThreadId, ""); var tclient = new System.Net.Sockets.TcpClient(); tclient.SendTimeout = SendTimeOutMS; tclient.NoDelay = true; tclient.Connect(ip, port); if (tclient.Connected) { var tstream = tclient.GetStream(); string link_msg = string.Format("{0}[{1}]:{2}:{3}\n", type, VERSION, topic, name + "_" + (NIndex++).ToString()); byte[] bs = System.Text.Encoding.UTF8.GetBytes(link_msg); tstream.Write(bs, 0, bs.Length); tstream.Flush(); int waittimes = 3; while (waittimes > 0 && tstream.DataAvailable == false) { waittimes--; Thread.Sleep(1000); } tclient.ReceiveTimeout = ConnectTimeOutSeconds * 1000; byte[] bsyes = new byte[10]; var count = tstream.Read(bsyes, 0, bsyes.Length); if (System.Text.Encoding.UTF8.GetString(bsyes.Take(count).ToArray()).Trim() != "yes") { tclient.Close(); throw new Exception("非法TCP服务端"); } tclient.ReceiveTimeout = ReadTimeOutMS; this.client = tclient; this.stream = tstream; this.LastServerPingTime = DateTime.Now; this.LastServerPongTime = this.LastServerPingTime; RLib.WatchLog.Loger.Log("打开tcp成功!" + Thread.CurrentThread.ManagedThreadId, ""); Console.WriteLine("打开tcp成功!" + Thread.CurrentThread.ManagedThreadId); return(true); } Console.WriteLine("打开连接失败:Connected=false" + Thread.CurrentThread.ManagedThreadId); RLib.WatchLog.Loger.Log("打开连接失败:Connected=false" + Thread.CurrentThread.ManagedThreadId, ""); return(false); } catch (Exception ex) { Console.WriteLine("打开连接失败:" + ex.Message); RLib.WatchLog.Loger.Log("打开tcp失败!" + Thread.CurrentThread.ManagedThreadId, ex.Message + Environment.NewLine + ex.StackTrace); RLib.WatchLog.Loger.Error("打开tcp失败!" + Thread.CurrentThread.ManagedThreadId, ex.Message + Environment.NewLine + ex.StackTrace); return(false); } finally { } }
public void Initialize(string rosBridgeIP, int sigverseBridgePort, string topicNameCameraInfo, string topicNameImage, bool isRight, bool isUsingThread) { if (!RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.ContainsKey(topicNameCameraInfo)) { this.tcpClientCameraInfo = SIGVerseRosBridgeConnection.GetConnection(rosBridgeIP, sigverseBridgePort); RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.Add(topicNameCameraInfo, this.tcpClientCameraInfo); } else { this.tcpClientCameraInfo = RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap[topicNameCameraInfo]; } if (!RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.ContainsKey(topicNameImage)) { this.tcpClientImage = SIGVerseRosBridgeConnection.GetConnection(rosBridgeIP, sigverseBridgePort); RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.Add(topicNameImage, this.tcpClientImage); } else { this.tcpClientImage = RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap[topicNameImage]; } this.networkStreamCameraInfo = this.tcpClientCameraInfo.GetStream(); this.networkStreamCameraInfo.ReadTimeout = 100000; this.networkStreamCameraInfo.WriteTimeout = 100000; this.networkStreamImage = this.tcpClientImage.GetStream(); this.networkStreamImage.ReadTimeout = 100000; this.networkStreamImage.WriteTimeout = 100000; // Camera this.targetCamera = this.cameraFrameObj.GetComponentInChildren <Camera>(); int imageWidth = this.targetCamera.targetTexture.width; int imageHeight = this.targetCamera.targetTexture.height; this.imageTexture = new Texture2D(imageWidth, imageHeight, TextureFormat.RGB24, false); // [CameraInfo] string distortionModel = "plumb_bob"; double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 }; double[] K = { 968.765, 0.0, 640, 0.0, 968.77, 480, 0.0, 0.0, 1.0 }; double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; double[] P = { 968.765, 0.0, 640, 0.0, 0.0, 968.77, 480, 0.0, 0.0, 0.0, 1.0, 0.0 }; if (isRight) { P[3] = -135.627; // -135.627 = - 968.765 * 0.14(baseline=distance between both eyes) } //double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 }; //double[] K = { 968.7653251755174, 0.0, 640.5, 0.0, 968.7653251755174, 480.5, 0.0, 0.0, 1.0 }; //double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; // Left Camera //double[] P = { 968.7653251755174, 0.0, 640.5, -0.0, 0.0, 968.7653251755174, 480.5, 0.0, 0.0, 0.0, 1.0, 0.0 }; // Right Camera //double[] P = { 968.7653251755174, 0.0, 640.5, -135.62714552457246, 0.0, 968.7653251755174, 480.5, 0.0, 0.0, 0.0, 1.0, 0.0 }; RegionOfInterest roi = new RegionOfInterest(0, 0, 0, 0, false); this.cameraInfoData = new CameraInfoForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, distortionModel, D, K, R, P, 0, 0, roi); // [Image_raw] string encoding = "rgb8"; byte isBigendian = 0; uint step = (uint)imageWidth * 3; this.imageData = new ImageForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, encoding, isBigendian, step, null); this.header = new Header(0, new SIGVerse.RosBridge.msg_helpers.Time(0, 0), this.cameraFrameObj.name); this.cameraInfoMsg = new SIGVerseRosBridgeMessage <CameraInfoForSIGVerseBridge>("publish", topicNameCameraInfo, CameraInfoForSIGVerseBridge.GetMessageType(), this.cameraInfoData); this.imageMsg = new SIGVerseRosBridgeMessage <ImageForSIGVerseBridge> ("publish", topicNameImage, ImageForSIGVerseBridge.GetMessageType(), this.imageData); this.isUsingThread = isUsingThread; }
internal static byte[] readDrive(string remoteHost, int port, ulong offset, ulong sizeToRead) { // Bytes must be read by sector if ((sizeToRead < 1)) { throw new System.ArgumentException("Size parameter cannot be null or 0 or less than 0!"); } if (((sizeToRead % 512) != 0)) { throw new System.ArgumentException("Size parameter must be divisible by 512"); } if (((offset % 512) != 0)) { throw new System.ArgumentException("Offset parameter must be divisible by 512"); } // Create a byte array to read into byte[] buf = new byte[sizeToRead]; // Read buf.Length bytes (sizeToRead) from offset try { byte[] request = new byte[12]; // Request Signature request[0] = 0x54; request[1] = 0x46; request[2] = 0x31; request[3] = 0x32; // Request Offset byte[] offsetBytes = new byte[4]; offsetBytes = BitConverter.GetBytes(offset); request[4] = offsetBytes[0]; request[5] = offsetBytes[1]; request[6] = offsetBytes[2]; request[7] = offsetBytes[3]; // Request Length byte[] lengthBytes = new byte[4]; lengthBytes = BitConverter.GetBytes(sizeToRead); request[8] = lengthBytes[0]; request[9] = lengthBytes[1]; request[10] = lengthBytes[2]; request[11] = lengthBytes[3]; System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(remoteHost, port); System.Net.Sockets.NetworkStream stream = client.GetStream(); stream.Write(request, 0, request.Length); int byteCount = stream.Read(buf, 0, buf.Length); if (byteCount != buf.Length) { throw new Exception("Error reading from NBD"); } stream.Close(); client.Close(); } catch { throw new Exception("Error setting up NBD network request"); } return(buf); }
protected override void OnWrite(System.Net.Sockets.NetworkStream stream, Server.Core.Stream.ByteBuffer buffer) { }
public void Initialize(string rosBridgeIP, int sigverseBridgePort, string topicNameCameraInfo, string topicNameImage) { if (rosBridgeIP.Equals(string.Empty)) { rosBridgeIP = ConfigManager.Instance.configInfo.rosbridgeIP; } if (sigverseBridgePort == 0) { sigverseBridgePort = ConfigManager.Instance.configInfo.sigverseBridgePort; } this.tcpClientCameraInfo = HSRCommon.GetSIGVerseRosbridgeConnection(rosBridgeIP, sigverseBridgePort); this.tcpClientImage = HSRCommon.GetSIGVerseRosbridgeConnection(rosBridgeIP, sigverseBridgePort); this.networkStreamCameraInfo = this.tcpClientCameraInfo.GetStream(); this.networkStreamCameraInfo.ReadTimeout = 100000; this.networkStreamCameraInfo.WriteTimeout = 100000; this.networkStreamImage = this.tcpClientImage.GetStream(); this.networkStreamImage.ReadTimeout = 100000; this.networkStreamImage.WriteTimeout = 100000; // RGB Camera this.rgbCamera = this.cameraFrameObj.GetComponentInChildren <Camera>(); int imageWidth = this.rgbCamera.targetTexture.width; int imageHeight = this.rgbCamera.targetTexture.height; this.imageTexture = new Texture2D(imageWidth, imageHeight, TextureFormat.RGB24, false); // [camera/rgb/CameraInfo] string distortionModel = "plumb_bob"; double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 }; double[] K = { 205.47, 0.0, 320, 0.0, 205.47, 240, 0.0, 0.0, 1.0 }; double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; double[] P = { 205.47, 0.0, 320, 0.0, 0.0, 205.47, 240, 0.0, 0.0, 0.0, 1.0, 0.0 }; //double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 }; //double[] K = { 205.46963709898583, 0.0, 320.5, 0.0, 205.46963709898583, 240.5, 0.0, 0.0, 1.0 }; //double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; //double[] P = { 205.46963709898583, 0.0, 320.5, 0.0, 0.0, 205.46963709898583, 240.5, 0.0, 0.0, 0.0, 1.0, 0.0 }; RegionOfInterest roi = new RegionOfInterest(0, 0, 0, 0, false); this.cameraInfoData = new CameraInfoForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, distortionModel, D, K, R, P, 0, 0, roi); // [camera/rgb/Image_raw] string encoding = "rgb8"; byte isBigendian = 0; uint step = (uint)imageWidth * 3; this.imageData = new ImageForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, encoding, isBigendian, step, null); this.header = new Header(0, new SIGVerse.ROSBridge.msg_helpers.Time(0, 0), this.cameraFrameObj.name); this.cameraInfoMsg = new SIGVerseROSBridgeMessage <CameraInfoForSIGVerseBridge>("publish", topicNameCameraInfo, CameraInfoForSIGVerseBridge.GetMessageType(), this.cameraInfoData); this.imageMsg = new SIGVerseROSBridgeMessage <ImageForSIGVerseBridge> ("publish", topicNameImage, ImageForSIGVerseBridge.GetMessageType(), this.imageData); }
public void Initialize(string rosBridgeIP, int sigverseBridgePort, string topicNameCameraInfo, string topicNameImage, bool isUsingThread) { if (!RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.ContainsKey(topicNameCameraInfo)) { this.tcpClientCameraInfo = SIGVerseRosBridgeConnection.GetConnection(rosBridgeIP, sigverseBridgePort); RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.Add(topicNameCameraInfo, this.tcpClientCameraInfo); } else { this.tcpClientCameraInfo = RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap[topicNameCameraInfo]; } if (!RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.ContainsKey(topicNameImage)) { this.tcpClientImage = SIGVerseRosBridgeConnection.GetConnection(rosBridgeIP, sigverseBridgePort); RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap.Add(topicNameImage, this.tcpClientImage); } else { this.tcpClientImage = RosConnectionManager.Instance.rosConnections.sigverseRosBridgeTcpClientMap[topicNameImage]; } this.networkStreamCameraInfo = this.tcpClientCameraInfo.GetStream(); this.networkStreamCameraInfo.ReadTimeout = 100000; this.networkStreamCameraInfo.WriteTimeout = 100000; this.networkStreamImage = this.tcpClientImage.GetStream(); this.networkStreamImage.ReadTimeout = 100000; this.networkStreamImage.WriteTimeout = 100000; // Depth Camera this.depthCamera = this.cameraFrameObj.GetComponentInChildren <Camera>(); int imageWidth = this.depthCamera.targetTexture.width; int imageHeight = this.depthCamera.targetTexture.height; this.byteArray = new byte[imageWidth * imageHeight * 2]; for (int i = 0; i < this.byteArray.Length; i++) { this.byteArray[i] = 0; } this.imageTexture = new Texture2D(imageWidth, imageHeight, TextureFormat.RGB24, false); // [camera/depth/CameraInfo] string distortionModel = "plumb_bob"; double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 }; double[] K = { 445, 0.0, 240, 0.0, 445, 180, 0.0, 0.0, 1.0 }; double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; double[] P = { 445, 0.0, 240, 0.0, 0.0, 445, 180, 0.0, 0.0, 0.0, 1.0, 0.0 }; // double[] D = { 0.0, 0.0, 0.0, 0.0, 0.0 }; // double[] K = { 455.84368896484375, 0.0, 225.90170288085938, 0.0, 455.84368896484375, 179.5, 0.0, 0.0, 1.0 }; // double[] R = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0 }; // double[] P = { 455.84368896484375, 0.0, 225.90170288085938, -0.058707427233457565, 0.0, 455.84368896484375, 179.5, -0.00020851753652095795, 0.0, 0.0, 1.0, -0.0005153142847120762 }; RegionOfInterest roi = new RegionOfInterest(0, 0, 0, 0, false); this.cameraInfoData = new CameraInfoForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, distortionModel, D, K, R, P, 0, 0, roi); // [camera/depth/Image_raw] string encoding = "16UC1"; byte isBigendian = 0; uint step = (uint)imageWidth * 2; this.imageData = new ImageForSIGVerseBridge(null, (uint)imageHeight, (uint)imageWidth, encoding, isBigendian, step, null); this.header = new Header(0, new SIGVerse.RosBridge.msg_helpers.Time(0, 0), this.cameraFrameObj.name); this.cameraInfoMsg = new SIGVerseRosBridgeMessage <CameraInfoForSIGVerseBridge>("publish", topicNameCameraInfo, CameraInfoForSIGVerseBridge.GetMessageType(), this.cameraInfoData); this.imageMsg = new SIGVerseRosBridgeMessage <ImageForSIGVerseBridge> ("publish", topicNameImage, ImageForSIGVerseBridge.GetMessageType(), this.imageData); this.isUsingThread = isUsingThread; }
public bool EnterLock() { if (ntsm == null) { throw new Exception("CriticalSection.EnterLock() failed: Network stream has already been closed due to previous exceptions."); } try { // acquire lock for (int iacq = 0; ;) { try { if (null == locknamebytes) { ntsm.WriteByte((byte)'Q'); } else { ntsm.WriteByte(128 + (byte)'Q'); // 128+Q XContent.SendXContent(ntsm, locknamebytes); } } catch { if (++iacq > 60 / 5) { throw; } System.Threading.Thread.Sleep(1000 * 5); _reopen(); continue; } break; } if (hasLock) { throw new Exception("CriticalSection.EnterLock() failed: cannot enter lock twice"); } if (ntsm.ReadByte() == (int)'+') { hasLock = true; return(true); } else { throw new Exception("CriticalSection.EnterLock() handshake failed."); } } catch { if (object.ReferenceEquals(this, currentSection)) { currentSection = null; } ntsm.Close(); ntsm = null; sock.Close(); sock = null; throw; } }
private void button3_Click(object sender, RoutedEventArgs e) { if (!socet) { try { string ipOrHost = textBox1.Text; int port = int.Parse(textBox2.Text); tcp = new System.Net.Sockets.TcpClient(ipOrHost, port); statusBarText.Text = "サーバー(" + ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Address + ":" + ((System.Net.IPEndPoint)tcp.Client.RemoteEndPoint).Port + ")と接続しました(" + ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Address + ":" + ((System.Net.IPEndPoint)tcp.Client.LocalEndPoint).Port + ")。"; //NetworkStreamを取得する ns = tcp.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; socet = true; } catch (FormatException)//入力がおかしい { MessageBox.Show("IPアドレス、ポート番号を正しく入力してください(半角)", "エラー"); } catch (System.Net.Sockets.SocketException)// { MessageBox.Show("Serverと接続できませんでした", "エラー"); } } }
/// <summary> /// 创建消息并发送到网络流 /// </summary> /// <param name="toUserId"></param> /// <param name="message"></param> /// <param name="ns"></param> /// <returns></returns> public static void SendChatToStream(int userId, int toUserId, string message, System.Net.Sockets.NetworkStream ns) { new Chat(-1, userId, toUserId, message).SendChatToStream(ns); }
public override void Open() { if (isRIndexEnabled()) { _OpenRIndex(); return; } try { if (state == ConnectionState.Open) { throw new Exception("Connnection is already open."); } string[] hosts = connstr.DataSource; Random rnd = new Random(unchecked(System.DateTime.Now.Millisecond + System.Threading.Thread.CurrentThread.ManagedThreadId)); int index = rnd.Next() % hosts.Length; string host = hosts[index]; for (int startindex = index; ; ) { try { sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); sock.Connect(host, 55902); break; } catch { sock.Close(); index++; if (index == hosts.Length) { index = 0; } if (index == startindex) { throw; } host = hosts[index]; } } netstm = new System.Net.Sockets.NetworkStream(sock); netstm.WriteByte((byte)'o'); //Open connection. if (buf.Length < 128) { buf = new byte[128]; } Utils.Int64ToBytes(connstr.BatchSize, buf, 0); XContent.SendXContent(netstm, buf, 8); { int optindex = 0; Utils.Int64ToBytes(connstr.BlockSize, buf, optindex); optindex += 8; Utils.Int32ToBytes(connstr.QOLimit, buf, optindex); optindex += 4; buf[optindex] = (byte)(connstr.FaultTolerantExecution ? 1 : 0); optindex += 1; XContent.SendXContent(netstm, buf, optindex); } XContent.SendXContent(netstm, string.Join(";", hosts)); if (netstm.ReadByte() != (byte)'+') { throw new Exception("Cannot connect to host. Handshake failed with protocol."); } sessionID = XContent.ReceiveXString(netstm, buf); state = ConnectionState.Open; } catch { Cleanup(); throw; } }
/// <summary> /// Pop Before Smtp認証のためPOPサーバに接続 /// </summary> /// <param name="serv">POPサーバー</param> /// <param name="port">POPポート番号</param> /// <param name="user">ユーザID</param> /// <param name="pass">パスワード</param> public void PopBeforeSmtp( String serv, int port, String user, String pass) { System.Net.Sockets.NetworkStream stream = null; System.Net.Sockets.TcpClient client = null; try { String rstr; client = new System.Net.Sockets.TcpClient(); // POPサーバーに接続 client.Connect(serv, port); stream = client.GetStream(); // POPサーバー接続時のレスポンス受信 rstr = WriteAndRead(stream, ""); if (rstr.IndexOf("+OK") != 0) { throw new Exception("POPサーバー接続エラー"); } // ユーザIDの送信 rstr = WriteAndRead(stream, "USER " + user + "\r\n"); if (rstr.IndexOf("+OK") != 0) { throw new Exception("ユーザIDエラー"); } // パスワードの送信 rstr = WriteAndRead(stream, "PASS " + pass + "\r\n"); if (rstr.IndexOf("+OK") != 0) { throw new Exception("パスワードエラー"); } //// APOPの場合は[ユーザID送信]と[パスワード送信]の処理を以下のように変更します //// POPサーバー接続時のレスポンスからAPOP用のキー(<>で囲まれた部分)を取得して //// パスワードと連結(例:"<*****@*****.**>PASS")してMD5(HEX)変換して //// "APOP user MD5(HEX)"形式で送信します //Byte[] byt = System.Text.Encoding.ASCII.GetBytes("<*****@*****.**>" + pass); //System.Security.Cryptography.MD5CryptoServiceProvider md5 = // new System.Security.Cryptography.MD5CryptoServiceProvider(); //Byte[] res = md5.ComputeHash(byt); //String aps = BitConverter.ToString(res).Replace("-", "").ToLower(); //rstr = WriteAndRead(stream, "APOP " + user + " " + aps + "\r\n"); //if (rstr.IndexOf("+OK") != 0) //{ // throw new Exception("ユーザIDまたはパスワードエラー"); //} // ステータスの送信 rstr = WriteAndRead(stream, "STAT" + "\r\n"); if (rstr.IndexOf("+OK") != 0) { throw new Exception("STATエラー"); } // 終了の送信 rstr = WriteAndRead(stream, "QUIT" + "\r\n"); } catch (Exception ex) { throw ex; } finally { if (stream != null) { stream.Close(); stream.Dispose(); } if (client != null) { client.Close(); } } }
// 接続待ちスレッド用メソッド private void ListeningCallback() { System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString); //ホスト名からIPアドレスを取得する時は、次のようにする //string host = "localhost"; //System.Net.IPAddress ipAdd = // System.Net.Dns.GetHostEntry(host).AddressList[0]; //.NET Framework 1.1以前では、以下のようにする //System.Net.IPAddress ipAdd = // System.Net.Dns.Resolve(host).AddressList[0]; //TcpListenerオブジェクトを作成する // System.Net.Sockets.TcpListener listener = listener = new System.Net.Sockets.TcpListener(ipAdd, port); Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port); //try //{ //Listenを開始する listener.Start(); //} //catch //{ // listener.Stop(); // listener = null; // return ; //} do { while (SLTAlive) { if (listener.Pending() == true) { //接続要求があったら受け入れる // System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); client = listener.AcceptTcpClient(); if (client.Connected == true) { Console.WriteLine("クライアント({0}:{1})と接続しました。", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port); //NetworkStreamを取得 ns = client.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; //クライアントから送られたデータを受信する System.Text.Encoding enc = System.Text.Encoding.UTF8; bool disconnected = false; 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) { disconnected = true; Console.WriteLine("クライアントが切断しました。"); break; } //受信したデータを蓄積する ms.Write(resBytes, 0, resSize); //まだ読み取れるデータがあるか、データの最後が\nでない時は、 // 受信を続ける } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); //受信したデータを文字列に変換 string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //末尾の\nを削除 resMsg = resMsg.TrimEnd('\n'); Console.WriteLine(resMsg); if (!disconnected) { //クライアントにデータを送信する //クライアントに送信する文字列を作成 string sendMsg = resMsg.Length.ToString(); //文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes(sendMsg + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); Console.WriteLine(sendMsg); } } } } // 短時間だけ待機 System.Threading.Thread.Sleep(100); } while (true); //閉じる // ns.Close(); // client.Close(); // Console.WriteLine("クライアントとの接続を閉じました。"); //リスナを閉じる // listener.Stop(); // Console.WriteLine("Listenerを閉じました。"); // Console.ReadLine(); }
/// <summary> /// Initialises a new instance of the <see cref="NetworkStream" /> class. /// </summary> /// <param name="stream">The stream.</param> public NetworkStream(System.Net.Sockets.NetworkStream stream) { this.stream = stream; }
protected void makeShouter() { logger.a("make shouter"); proc.PriorityClass = System.Diagnostics.ProcessPriorityClass.AboveNormal; if (string.IsNullOrEmpty(settings.host)) { s = null; rekick = 0; stampee = 0; stdin = pstdin; stdout = pstdout; stamps = new long[32]; chunks = new long[32]; long v = DateTime.UtcNow.Ticks / 10000; for (int a = 0; a < stamps.Length; a++) stamps[a] = v; System.Threading.Thread tr = new System.Threading.Thread(new System.Threading.ThreadStart(reader)); tr.Name = "LSEnc_Reader"; tr.Start(); System.Threading.Thread tc = new System.Threading.Thread(new System.Threading.ThreadStart(counter)); tc.Name = "LSEnc_Counter"; tc.Start(); return; } System.Net.Sockets.NetworkStream prepS; string ver = Application.ProductVersion; string auth = string.Format("{0}:{1}", settings.user, settings.pass); auth = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(auth)); byte[] header; if (enc.ext == "mp3") { header = System.Text.Encoding.UTF8.GetBytes(string.Format( "SOURCE /{1}.{2} HTTP/1.0{0}" + "Authorization: Basic {3}{0}" + "User-Agent: loopstream/{4}{0}" + "Content-Type: audio/mpeg{0}" + "ice-name: {5}{0}" + "ice-public: {6}{0}" + "ice-url: {7}{0}" + "ice-genre: {8}{0}" + "ice-audio-info: channels={9};samplerate={10};{11}={12}{0}" + "ice-description: {13}{0}{0}", "\r\n", settings.mount, enc.ext, auth, ver, esc(settings.title), settings.pubstream ? "1" : "0", esc(settings.url), esc(settings.genre), enc.channels == LSSettings.LSChannels.stereo ? 2 : 1, settings.samplerate, enc.compression == LSSettings.LSCompression.cbr ? "bitrate" : "quality", enc.compression == LSSettings.LSCompression.cbr ? "" + enc.bitrate : enc.quality + ".0", esc(settings.description) )); } else { header = System.Text.Encoding.UTF8.GetBytes(string.Format( "SOURCE /{1}.{2} ICE/1.0{0}" + "Content-Type: application/ogg{0}" + "Authorization: Basic {3}{0}" + "User-Agent: loopstream/{4}{0}" + "ice-name: {5}{0}" + "ice-url: {6}{0}" + "ice-genre: {7}{0}" + "ice-bitrate: {8}{0}" + "ice-private: {9}{0}" + "ice-public: {10}{0}" + "ice-description: {11}{0}" + "ice-audio-info: ice-samplerate={12};ice-channels={13};ice-bitrate={8}{0}{0}", "\r\n", settings.mount, enc.ext, auth, ver, esc(settings.title), esc(settings.url), esc(settings.genre), enc.compression == LSSettings.LSCompression.cbr ? enc.bitrate + "" : "Quality " + enc.quality, settings.pubstream ? "0" : "1", // why settings.pubstream ? "1" : "0", esc(settings.description), settings.samplerate, enc.channels == LSSettings.LSChannels.stereo ? 2 : 1)); } string str = "(no reply)"; try { logger.a("making socket"); tc = new System.Net.Sockets.TcpClient(); tc.Connect(settings.host, settings.port); logger.a("socket connected"); prepS = tc.GetStream(); prepS.Write(header, 0, header.Length); logger.a("headers sent"); int i = prepS.Read(header, 0, header.Length); str = System.Text.Encoding.UTF8.GetString(header, 0, i); logger.a("socket alive"); } catch (Exception e) { Program.ni.ShowBalloonTip(9999, "Server connection error", e.Message + " (" + e.Source + ")", ToolTipIcon.Error); System.Threading.Thread.Sleep(200); crashed = true; return; } if (str.StartsWith("HTTP/1.0 401 Unauthorized")) { MessageBox.Show("Radio server error: Wrong password", "Stream abort", MessageBoxButtons.OK, MessageBoxIcon.Error); } else if (str.StartsWith("HTTP/1.0 403 Mountpoint in use")) { if (--rekick > 0) { crashed = true; } else if (DialogResult.Yes == MessageBox.Show( "Someone are already connected to the server.\n\nTry to kick them?", "Mountpoint in use", MessageBoxButtons.YesNo)) { byte[] kickrequest = System.Text.Encoding.UTF8.GetBytes(string.Format( "GET /admin/killsource?mount=/{1}.{2} HTTP/1.0{0}" + "Authorization: Basic {3}{0}" + "User-Agent: loopstream/{4}{0}" + "Content-Type: audio/mpeg{0}{0}", "\r\n", settings.mount, enc.ext, auth, ver )); logger.a("kicker socket"); var kc = new System.Net.Sockets.TcpClient(); kc.Connect(settings.host, settings.port); logger.a("kicker connected"); var ks = kc.GetStream(); ks.Write(kickrequest, 0, kickrequest.Length); ks.Flush(); logger.a("kicker sent"); int i = ks.Read(kickrequest, 0, kickrequest.Length); string kickresult = System.Text.Encoding.UTF8.GetString(kickrequest, 0, i); logger.a("kicker done"); rekick = 5; crashed = true; } else { aborted = true; } } else if (str.StartsWith("HTTP/1.0 200 OK")) { logger.a("bootstrap"); s = prepS; rekick = 0; stampee = 0; stdin = pstdin; stdout = pstdout; s.WriteTimeout = 1000; stamps = new long[32]; chunks = new long[32]; long v = DateTime.UtcNow.Ticks / 10000; for (int a = 0; a < stamps.Length; a++) stamps[a] = v; Program.ni.ShowBalloonTip(1000, "Loopstream Connected", "Streaming to " + settings.mount + "." + enc.ext, ToolTipIcon.Info); System.Threading.Thread tr = new System.Threading.Thread(new System.Threading.ThreadStart(reader)); tr.Name = "LSEnc_Reader"; tr.Start(); System.Threading.Thread tc = new System.Threading.Thread(new System.Threading.ThreadStart(counter)); tc.Name = "LSEnc_Counter"; tc.Start(); } else { MessageBox.Show("Unknown radio server error:\n\n" + str, "Stream abort", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/** 別のプログラムと通信するための処理 */ 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 を終了します."); }
public static int Main(String[] args) { // instantiate backend implementation using (feature.IxxatCAN.AbstractCANHandle handle = new feature.IxxatCAN.handle.ActiveSeatHandle()) { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : instantiated ActiveSeat IxxatCAN handle" ); // initialize it handle.SelectDevice(); handle.InitSocket(0); Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : backend IxxatCAN handle intialized" ); // instantiate a client connection with the first non-ipv6 address Int32 client_port = 0, // any server_port = 8888; // same as server System.Net.IPEndPoint localEndPoint = new System.Net.IPEndPoint( System.Net.IPAddress.Loopback, client_port ); System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint( System.Net.IPAddress.Loopback, server_port ); using (System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(localEndPoint)) { // connect client.Connect(remoteEndPoint); // some status boolean bool bEndSession = false; // Get a client stream for reading and writing. using (System.Net.Sockets.NetworkStream stream = client.GetStream()) { // double slot byte[] data = new byte[256]; // until end session do { // Wait for 'messages' from the unity app server. Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : Wait for messages..." ); // Read the batch of the TcpServer response bytes. switch ((messageID)System.Convert.ToInt16(stream.ReadByte())) { case messageID.BeginSession: { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : received [BeginSession]." ); //(handle as handle.ActiveSeatHandle).BeginSession(); } break; case messageID.BeginTrial: { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : received [BeginTrial]." ); //(handle as handle.ActiveSeatHandle).BeginTrial(); } break; case messageID.Start: { // 3 messages /* 1st - [ in: rad/s^2 (SI) | out: deg/s^2 ] */ stream.Read(data, 0, 8); System.Double dAngularAcceleration /* extract */ = System.BitConverter.ToDouble(data, 0) /* rad -> deg */ * (180.0 / System.Math.PI) /* trigo. way */ * -1.0; /* 2nd - [ in: rad/s (SI) | out: s ] */ stream.Read(data, 0, 8); System.Double dAngularVelocity /* extract */ = System.BitConverter.ToDouble(data, 0) /* rad -> deg */ * (180.0 / System.Math.PI) /* trigo. way */ * -1.0; /* 3rd - [ in: ms (SI) | out: s ] */ stream.Read(data, 0, 8); System.Double dMaxStimDuration /* extract */ = System.BitConverter.ToDouble(data, 0) /* ms -> s */ / 1000.0; Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : received [Start] with args [" + dAngularVelocity + "], [" + dAngularVelocity / dAngularAcceleration + "], [" + dMaxStimDuration + "] !" ); (handle as feature.IxxatCAN.handle.ActiveSeatHandle).Start( /* ISM - deg/s */ dAngularVelocity, /* ISM - rise time */ dAngularVelocity / dAngularAcceleration, /* ISM - max time */ dMaxStimDuration ); } break; case messageID.Stop: { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : received [Stop]." ); //(handle as handle.ActiveSeatHandle).Stop(); } break; case messageID.Reset: { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : received [Reset]." ); //(handle as handle.ActiveSeatHandle).Reset(); } break; case messageID.EndTrial: { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : received [EndTrial]." ); //(handle as handle.ActiveSeatHandle).EndTrial(); } break; case messageID.EndSession: { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : received [EndSession]." ); //(handle as handle.ActiveSeatHandle).EndSession(); bEndSession = true; } break; case messageID.NoMoreData: { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- INFO : waiting for fresh data." ); } break; default: { Console.WriteLine( DateTime.Now.ToString("HH:mm:ss.ffffff") + " - [Apollon-gateway-ActiveSeat] -- ERROR : received [UNKNOWN]." ); bEndSession = true; } break; } /* switch() */ } while (!bEndSession); // close & dispose stream.Close(); } /* using (stream) */ // close & dispose client.Close(); } /* using (client) */ } /* using (handle)*/ // success return(0); } /* static Main */
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; } }
private static void HandleClient(object data) { try { System.Net.Sockets.TcpClient connection = (System.Net.Sockets.TcpClient)data; core.DebugLog("Incoming connection from: " + connection.Client.RemoteEndPoint.ToString()); Connections++; connection.NoDelay = true; System.Net.Sockets.NetworkStream ns = connection.GetStream(); System.IO.StreamReader Reader = new System.IO.StreamReader(ns); string text; // give the user access to global cache // save the reference to global cache because we might need it in future System.IO.StreamWriter Writer = new System.IO.StreamWriter(ns); // login Writer.WriteLine("Enter username:"******"Enter password:"******"Invalid user or password, bye"); Writer.Flush(); connection.Close(); Connections--; return; } Writer.WriteLine("Successfuly logged in to wm-bot, I have " + Connections.ToString() + " users logged in"); Writer.Flush(); while (connection.Connected && !Reader.EndOfStream) { text = Reader.ReadLine(); string command = text; List <string> list = new List <string>(); string parameters = ""; if (command.Contains(" ")) { parameters = command.Substring(command.IndexOf(" ") + 1); command = command.Substring(0, command.IndexOf(" ")); if (parameters.Contains(" ")) { list.AddRange(parameters.Split(' ')); } } switch (command.ToLower()) { case "exit": Writer.WriteLine("Good bye"); Writer.Flush(); connection.Close(); Connections--; return; case "info": string result = "Uptime: " + core.getUptime() + Environment.NewLine + "Instances:" + Environment.NewLine; lock (core.Instances) { foreach (Instance instance in core.Instances.Values) { result += instance.Nick + " channels: " + instance.ChannelCount.ToString() + " connected: " + instance.IsConnected.ToString() + " working: " + instance.IsWorking.ToString() + "\n"; } } Writer.WriteLine(result); Writer.Flush(); break; case "help": Writer.WriteLine("Commands:\n" + "exit - shutdown connection\n" + "info - print information about system\n" + "halt - shutdown bot\n" + "traffic-on - turn on traffic logs\n" + "traffic-off - turn off traffic logs\n" + "kill [instance] - disconnect selected instance\n" + "conn [instance] - connect instance\n"); Writer.Flush(); break; case "halt": Writer.WriteLine("Shutting down"); Writer.Flush(); core.Kill(); return; case "traffic-on": config.Logging = true; Writer.WriteLine("Dumping traffic"); Writer.Flush(); break; case "traffic-off": config.Logging = false; Writer.WriteLine("Disabled traf"); Writer.Flush(); break; case "kill": if (core.Instances.ContainsKey(parameters)) { core.Instances[parameters].irc.Disconnect(); Writer.WriteLine("Offline: " + parameters); Writer.Flush(); break; } Writer.WriteLine("Unknown instance: " + parameters); Writer.Flush(); break; case "conn": if (core.Instances.ContainsKey(parameters)) { if (core.Instances[parameters].irc.IsConnected) { Writer.WriteLine("Refusing to connect instance which is already connected: " + parameters); Writer.Flush(); break; } core.Instances[parameters].Init(); Writer.WriteLine("Initializing: " + parameters); Writer.Flush(); int curr = 0; while (curr < 10 && !core.Instances[parameters].IsWorking) { curr++; Thread.Sleep(1000); } if (!core.Instances[parameters].IsWorking) { Writer.WriteLine("Failed to initialize instance"); Writer.Flush(); break; } Writer.WriteLine("Joining channels"); Writer.Flush(); core.Instances[parameters].irc.ChannelsJoined = false; core.Instances[parameters].Join(); curr = 0; while (curr < core.Instances[parameters].ChannelCount && !core.Instances[parameters].irc.ChannelsJoined) { curr++; Thread.Sleep(6000); } if (!core.Instances[parameters].irc.ChannelsJoined) { Writer.WriteLine("Failed to rejoin all channels in time"); Writer.Flush(); break; } Writer.WriteLine("Instance is online: " + parameters); Writer.Flush(); break; } Writer.WriteLine("Unknown instance: " + parameters); Writer.Flush(); break; case "send": if (!parameters.Contains(" ")) { Writer.WriteLine("This command requires 2 parameters"); Writer.Flush(); break; } string to = parameters.Substring(0, parameters.IndexOf(" ")); if (core.Instances.ContainsKey(to)) { if (!core.Instances[to].irc.IsConnected) { Writer.WriteLine("Refusing to send data using instance which is not connected: " + to); Writer.Flush(); break; } core.Instances[to].irc.SendData(parameters.Substring(parameters.IndexOf(" ") + 1)); break; } Writer.WriteLine("I have no such instance dude"); Writer.Flush(); break; default: Writer.WriteLine("Unknown command, try help"); Writer.Flush(); break; } } } catch (Exception fail) { core.handleException(fail); } Connections--; }
public Boolean AcceptClient() { Console.WriteLine("クライアントと接続待ち。"); Client = Listener.AcceptTcpClient(); Console.WriteLine( string.Format("クライアント({0},{1})と接続しました。", ((System.Net.IPEndPoint)Client.Client.RemoteEndPoint).Address, ((System.Net.IPEndPoint)Client.Client.RemoteEndPoint).Port) ); System.Net.Sockets.NetworkStream ns = Client.GetStream(); ns.ReadTimeout = ReadTimeout; ns.WriteTimeout = WriteTimeout; System.Text.Encoding enc = System.Text.Encoding.UTF8; Boolean disconnected = false; do { System.IO.MemoryStream ms = new System.IO.MemoryStream(); int resSize = 0; byte[] resBytes = new byte[1024]; try { do { resSize = ns.Read(resBytes, 0, resBytes.Length); if (resSize == 0) { disconnected = true; Console.WriteLine("クライアントが切断しました。"); break; } ms.Write(resBytes, 0, resSize); //ns.Write(resBytes, 0, resSize); } while (ns.DataAvailable || resBytes[resSize - 1] != '\n'); } catch (IOException e) { disconnected = true; Console.WriteLine("Read Timeoutで切断しました。" + e); } string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length); ms.Close(); //Console.WriteLine("[" + resMsg + "]"); if (disconnected) { //メッセージ解析 //返信処理 Console.WriteLine("通信終了。"); } else { //メッセージ解析 disconnected = !msg.Input(resMsg); //msg.Input(resMsg); //返信処理 string sendMsg = msg.Output(); byte[] sendByte = enc.GetBytes(sendMsg + "\n"); byte[] sendData = msg.OutputBinary(); try { ns.Write(sendByte, 0, sendByte.Length); ns.Write(sendData, 0, sendData.Length); } catch (IOException e) { disconnected = true; Console.WriteLine("Write Timeoutで切断しました。" + e); } //Console.WriteLine("[" + sendMsg + "]" + " 送信。"); Console.WriteLine("送信 text:" + sendByte.Length.ToString() + "bytes, binary:" + sendData.Length.ToString()); } } while (!disconnected); ns.Close(); Client.Close(); return(true); }
/// <summary> /// Creates a new isntance of a WebRequest object /// parameters: /// front: is a seekable stream to represent the first part of the request body with it position set to be just after the double line break /// back: is another stream that contains the rest of the body /// headers: is a concurent dictionary of normalized headers from the http request /// method: is a string representing the method from the HTTP Request (GET, POST, DELETE ect...) /// requestTarget: is a the desired uri from the HTTP Request /// httpVersion: is the version from the HTTP Request /// /// </summary> public WebRequest(Stream front, Stream back, ConcurrentDictionary <string, string> headers, string method, string requestTarget, string httpVersion, System.Net.Sockets.NetworkStream nStream) { if (headers.ContainsKey("content-length")) { long length = Convert.ToInt64(headers["content-length"]); _body = new ConcatStream(front, back, length); } else { _body = new ConcatStream(front, back); } _headers = headers; _method = method; _requestTarget = requestTarget; _httpVersion = httpVersion; _response = nStream; }
static public string[] GetUrlList() { //ListenするIPアドレス string ipString = "localhost"; System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString); //Listenするポート番号 int port = 8080; //TcpListenerオブジェクトを作成する System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAdd, port); //Listenを開始する listener.Start(); //接続要求があったら受け入れる System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); //NetworkStreamを取得 System.Net.Sockets.NetworkStream ns = client.GetStream(); //読み取り、書き込みのタイムアウトを10秒にする //デフォルトはInfiniteで、タイムアウトしない //(.NET Framework 2.0以上が必要) ns.ReadTimeout = 10000; ns.WriteTimeout = 10000; //クライアントから送られたデータを受信する bool disconnected = false; List <string> urlList = new List <string>(); while (true) { string url = GetUrl(ns); if (url == null) { disconnected = true; break; } else { urlList.Add(url); } } if (!disconnected) { //クライアントにデータを送信する //クライアントに送信する文字列を作成 //文字列をByte型配列に変換 byte[] sendBytes = enc.GetBytes("草生える" + '\n'); //データを送信する ns.Write(sendBytes, 0, sendBytes.Length); } //閉じる ns.Close(); client.Close(); //リスナを閉じる listener.Stop(); return(urlList.ToArray()); }
public VitalsReporter(long jobID, System.Net.Sockets.NetworkStream netstm) { jobid = jobID; clientstm = netstm; }
//unused in a TcpListener, because messages actually handled in TcpClient which spins off this listener on connection made. private byte[] ReceiveBytes(int timeout, System.Net.Sockets.NetworkStream stream) { return(new byte[256]); }
protected override void ProcessCommand(System.Net.Sockets.NetworkStream nstm, char tag) { int len; switch (tag) { case 'R': // Remote! { string classname = XContent.ReceiveXString(nstm, buf); string xlibfn = CreateXlibFileName("remote"); { buf = XContent.ReceiveXBytes(nstm, out len, buf); if (0 != len) { System.IO.FileStream stm = System.IO.File.Create(xlibfn); stm.Write(buf, 0, len); stm.Close(); } } string dllfn = CreateDllFileName("remote"); { buf = XContent.ReceiveXBytes(nstm, out len, buf); System.IO.FileStream stm = System.IO.File.Create(dllfn); stm.Write(buf, 0, len); stm.Close(); } if (XLog.logging) { string xclassname = classname; if (null == xclassname) { xclassname = "<null>"; } XLog.log("Loading IRemote plugin named " + xclassname + " for remote: " + dllfn); } rem = LoadRemotePlugin(dllfn, classname); #if DEBUG try { rem.OnRemote(); } catch (Exception e) { throw new UserException(e); } #else rem.OnRemote(); #endif } break; case 'O': //Query DGlobals { int byteCount = DGlobalsM.ToBytes(ref buf); XContent.SendXContent(nstm, buf, byteCount); } break; case 'r': { buf = XContent.ReceiveXBytes(nstm, out len, buf); int n = Entry.BytesToInt(buf); int count = 0; if (null != rem) { List <long> appendsizes = new List <long>(); try { count = rem.GetOutputFileCount(n, appendsizes); } catch (Exception e) { throw new DistributedObjectsSlave.DistObjectAbortException(e); } if (buf.Length < 4 + 8 * appendsizes.Count) { buf = new byte[Entry.Round2Power(4 + 8 * appendsizes.Count)]; } Entry.ToBytes(count, buf, 0); int offset = 4; for (int i = 0; i < appendsizes.Count; i++, offset += 8) { Entry.LongToBytes(appendsizes[i], buf, offset); } XContent.SendXContent(nstm, buf, 4 + 8 * appendsizes.Count); break; // ! } Entry.ToBytes(count, buf, 0); XContent.SendXContent(nstm, buf, 4); } break; default: base.ProcessCommand(nstm, tag); break; } }
private void _OpenSocketRIndex(string host) { if (connstr.RIndex == QaConnectionString.RIndexType.POOLED && sockpool != null && sockpool.Count > 0) { if (host == null || host.Length == 0) { foreach (System.Net.Sockets.Socket sk in sockpool.Values) { sock = sk; break; } foreach (System.Net.Sockets.NetworkStream ns in netstmpool.Values) { netstm = ns; break; } return; } else { string _host = host.ToUpper(); if (sockpool.ContainsKey(_host)) { sock = sockpool[_host]; netstm = netstmpool[_host]; return; } } } try { int tryremains = connstr.RetryMaxCount; string[] hosts = null; Random rnd = null; for (; ; ) { try { if (host == null || host.Length == 0) { if (rnd == null) { rnd = new Random(unchecked(System.DateTime.Now.Millisecond + System.Threading.Thread.CurrentThread.ManagedThreadId)); hosts = connstr.DataSource; } int index = rnd.Next() % hosts.Length; host = hosts[index]; for (int startindex = index; ; ) { try { sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); sock.Connect(host, 55904); break; } catch { sock.Close(); index++; if (index == hosts.Length) { index = 0; } if (index == startindex) { throw; } host = hosts[index]; } } } else { sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); sock.Connect(host, 55904); } break; } catch (Exception ex) { if (connstr.RIndex == QaConnectionString.RIndexType.POOLED) { if (--tryremains <= 0) { throw new Exception("Cannot connect. Tried this many of times to connect already: " + tryremains.ToString() + ". RetryMaxCount=" + connstr.RetryMaxCount.ToString() + ". RetrySleep=" + connstr.RetrySleep.ToString() + ". " + ex.ToString()); } System.Threading.Thread.Sleep(connstr.RetrySleep); } else { throw; } } } netstm = new System.Net.Sockets.NetworkStream(sock, true); // Owned. if (connstr.RIndex == QaConnectionString.RIndexType.POOLED) { string _host = host.ToUpper(); if (sockpool == null) { sockpool = new Dictionary<string, System.Net.Sockets.Socket>(); netstmpool = new Dictionary<string, System.Net.Sockets.NetworkStream>(); } sockpool.Add(_host, sock); netstmpool.Add(_host, netstm); } } catch { Cleanup(); throw; } }
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; }
private void Cleanup() { if (netstm != null) { netstm.Close(); netstm = null; } if (sock != null) { sock.Close(); sock = null; } if (netstmpool != null) { foreach (System.Net.Sockets.NetworkStream ns in netstmpool.Values) { ns.Close(); } netstmpool = null; } if (sockpool != null) { foreach (System.Net.Sockets.Socket sk in sockpool.Values) { sk.Close(); } sockpool = null; } }
// // // // private void Initialize() { //Random ran = new Random(DateTime.Now.Millisecond); DateTime date = DateTime.Today; string serverResponse = string.Empty; int serverIndex = 0; bool keepTrying = true; while (keepTrying && serverIndex < m_NistServers.Length) { try { // Open a StreamReader to server string serverName = m_NistServers[serverIndex]; int serverPort = 13; System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(serverName, serverPort); client.ReceiveTimeout = 1; System.Net.Sockets.NetworkStream stream = client.GetStream(); stream.ReadTimeout = 1; StreamReader reader = new StreamReader(client.GetStream()); serverResponse = reader.ReadToEnd(); reader.Close(); DateTime systemTime = DateTime.Now; string[] elements = serverResponse.Split(new char[] { ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries); // Check to see that the signiture is there //if (serverResponse.Length > 47 && serverResponse.Substring(38, 9).Equals("UTC(NIST)")) if (elements != null && elements.Length >= 7 && String.Equals(elements[7], "UTC(NIST)", StringComparison.CurrentCultureIgnoreCase)) { int modJulianDate = int.Parse(elements[0]); // date - original method //string[] s = elements[1].Split(new char[]{'-'},StringSplitOptions.RemoveEmptyEntries); //int yr = int.Parse(s[0]); //int mo = int.Parse(s[1]); //int dd = int.Parse(s[2]); //if (modJulianDate > 51544) yr += 2000; else yr += 1999; // time //string[] s = elements[2].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); //int hr = int.Parse(s[0]); //int mm = int.Parse(s[1]); //int ss = int.Parse(s[2]); //DateTime nistTime = new DateTime(yr, mo, dd, hr, mm, ss); // New method DateTime nistTime = new DateTime(1858, 11, 17); // base modified julian date. nistTime = nistTime.AddDays(modJulianDate); nistTime = nistTime.Add(TimeSpan.Parse(elements[2])); nistTime = nistTime.ToLocalTime(); //convert to local time. // flags int dayLightCode = int.Parse(elements[3]); int leapSecCode = int.Parse(elements[4]); int healthCode = int.Parse(elements[5]); double msAdvance = double.Parse(elements[6]); // elements[7] = "UTC(NIST)" // elements[8] = "*"; // on-time-messsage // // Now estimate correction. // if (dayLightCode > 0) { m_IsDayLightSavingsInEffect = true; } TimeSpan systemOffset = nistTime.Subtract(systemTime); if (healthCode == 0) { m_SystemTimeList.Add(systemTime); m_SystemOffsetList.Add(systemOffset); string msg = string.Format("NIST server #{1} at {2} is healthy: Offset = {0}.", systemOffset.ToString(), serverIndex.ToString(), m_NistServers[serverIndex]); lock (m_MessagesLock) { m_Messages.Add(string.Format("{0} {1}", DateTime.Now.ToShortTimeString(), msg)); } Console.WriteLine(msg); } else { string msg = string.Format("NIST server #{1} at {2} is NOT healthy: Offset = {0}.", systemOffset.ToString(), serverIndex.ToString(), m_NistServers[serverIndex]); lock (m_MessagesLock) { m_Messages.Add(string.Format("{0} {1}", DateTime.Now.ToShortTimeString(), msg)); } Console.WriteLine(msg); } // Usage: //DateTime correctTimeEstimate = m_SystemTime.Add(m_SystemOffset); // use this! } else { string msg = string.Format("NIST server #{1} at {2} gave short response: Response = {0}.", serverResponse, serverIndex.ToString(), m_NistServers[serverIndex]); lock (m_MessagesLock) { m_Messages.Add(string.Format("{0} {1}", DateTime.Now.ToShortTimeString(), msg)); } Console.WriteLine(msg); } } catch (Exception e) { string msg = string.Format("NIST server #{1} at {2} failed. \nException = {0}.", e.Message, serverIndex.ToString(), m_NistServers[serverIndex]); lock (m_MessagesLock) { m_Messages.Add(string.Format("{0} {1}", DateTime.Now.ToShortTimeString(), msg)); } Console.WriteLine(msg); //System.Windows.Forms.MessageBox.Show(msg, "Failed to connect to NIST."); } serverIndex++; } //wend if (m_SystemOffsetList.Count > 0) { // Analyze results double aveOffset = 0; for (int i = 0; i < m_SystemOffsetList.Count; ++i) { aveOffset += m_SystemOffsetList[i].TotalSeconds; } aveOffset = aveOffset / m_SystemOffsetList.Count; int hours = (int)Math.Floor(aveOffset / 3600.0); aveOffset -= 3600.0 * hours; int mins = (int)Math.Floor(aveOffset / 60.0); aveOffset -= 60.0 * mins; int secs = (int)Math.Floor(aveOffset); aveOffset -= secs; int msecs = (int)Math.Floor(aveOffset * 1000.0); m_SystemOffset = new TimeSpan(0, hours, mins, secs, msecs); m_IsGood = true; } } //Initialize()
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) { } } }
/* * public PcapStreamReader(System.Net.Security.SslStream pcapStream, int packetQueueSize, StreamReadCompletedCallback streamReadCompletedCallback, bool startBackgroundWorkers, long streamMaxLength) * : this(pcapStream, packetQueueSize, streamReadCompletedCallback, startBackgroundWorkers, long.MaxValue, pcapStream.ReadTimeout) { } */ public PcapStreamReader(System.Net.Sockets.NetworkStream pcapStream, int packetQueueSize, StreamReadCompletedCallback streamReadCompletedCallback, bool startBackgroundWorkers, long streamMaxLength) : this(pcapStream, packetQueueSize, streamReadCompletedCallback, startBackgroundWorkers, long.MaxValue, pcapStream.ReadTimeout) { }