日期:2014-05-17  浏览次数:20888 次

C# SOCKET通信
1、socket通信中,不利用委托和事件能接收数据么?
2、我要做个TCP通信客户端,每次往服务器端发一个字符串然后接收返回的数据就好,这个需要做异步么?不用事件驱动能完成么?
------最佳解决方案--------------------
最好开线程.
------其他解决方案--------------------
开线程把接受程序放进里面?关键是我不知道怎么能用事件和委托在每次有数据的时候就能触发接受程序呢?
------其他解决方案--------------------

 TcpClient tcpClient;
        BackgroundWorker bgWorkder = new BackgroundWorker();

 if (tcpClient != null)
            {          
                tcpClient.Close();                
                tcpClient=null;
            }
  try
           {
            IPAddress ip = IPAddress.Parse(txtIp.Text);
            IPEndPoint ipPoint = new IPEndPoint(ip, Convert.ToInt16(txtPort.Text));
            tcpClient = new TcpClient();
            tcpClient.Connect(ipPoint);            
            NetworkStream nStream = tcpClient.GetStream();
            nStream.Write(bytTotal, 0, bytTotal.Length);
           }
           catch(System.Net.Sockets.SocketException ex)
           {
            MessageBox.Show("连接失败!");
                BaseTool.LogError(ex);
                return;
           }
catch (Exception ex)
            {
                BaseTool.LogError(ex);
                MessageBox.Show("未知异常:" + ex.Message);
                return;
            }

           bgWorkder.CancelAsync();
            bgWorkder.Dispose();      
          
            bgWorkder = new BackgroundWorker();
            bgWorkder.WorkerSupportsCancellation = true;
 &n