- 爱易网页
 
                        - 
                            C#教程
 
                        - 关于socket通信有关问题,为什么这段程序会有有关问题 
 
                         
                    
                    
                    日期:2014-05-18  浏览次数:20870 次 
                    
                        
                         关于socket通信问题,为什么这段程序会有问题
自己建立的sys类 
  
                         public   static   NetworkStream   ns   =   null; 
                         public   static   StreamReader   sr   =   null; 
                         public   static   TcpClient   clientsocket   =   null; 
                          
                         ///    <summary>  
                         ///   向服务器发起SOCKET请求 
                         ///    </summary>  
                         ///    <param   name= "import "> 发起的请求字符串 </param>  
                         ///    <returns> 返回服务器结果 </returns>  
                         public   static   string   sendSoket(string   import) 
                         { 
                                     string   sendSoket_   =    " "; 
                                     try 
                                     { 
                                                 Byte[]   outbytes   =   Encoding.GetEncoding( "GB2312 ").GetBytes(import.ToCharArray()); 
                                                 sys.ns.Write(outbytes,   0,   outbytes.Length);    
                                                 string   serverresponse   =    " "; 
                                                 serverresponse   =   sys.sr.ReadLine(); 
                                                 sendSoket_   =   serverresponse.Trim(); 
                                     } 
                                     catch   (Exception   ex) 
                                     { 
                                                 sendSoket_   =    "Exc| "   +   ex.ToString(); 
                                     } 
                                     return   sendSoket_; 
                         } 
  
 为什么软件会死掉,这个程序有什么问题吗? 
------解决方案--------------------
这一段好像不会导致死机。
------解决方案--------------------
是否因为TcpClient、NetworkStream是同步方式通信的?通信对方不响应的话自然会被阻塞掉。而如果恰好你这段程序在主线程中执行,这个软件就没响应了。 
 如果要在其它线程中读写NetworkStream中的内容,考虑使用 BeginWrite 和 EndWrite,如果要异步传输只能抛弃TcpClient了……