日期:2014-05-18  浏览次数:21061 次

socket 异步通信问题,请教!每次发送消息前都要进行重新连接
服务器端代码:
  ///监听
  private void listen()
  {
  // Data buffer for incoming data. 
  byte[] bytes = new Byte[2048];

  // Create a TCP/IP socket. 
  listener = new Socket(AddressFamily.InterNetwork,
  SocketType.Stream, ProtocolType.Tcp);
  // Bind the socket to the local endpoint and listen for incoming connections. 
  try
  {
  listener.Bind(localIpe);
  listener.Listen(100);
  Thread _acceptWorkThread = new Thread(AcceptWorkThread);
  _acceptWorkThread.Start();
   
  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }

  }
   
 
  private void AcceptWorkThread()
  {
  while (true)
  {
  //allDone.Reset();

  Socket socket= listener.Accept();
   
  // Wait until a connection is made before continuing. 
   
  // Create the state object. 
  StateObject state = new StateObject();
  state.workSocket = socket;
  socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
  ReadCallback, state);
  }
  }
   
  /// <summary>
  /// 异步处理函数
  /// </summary>
  /// <param name="ar"></param>
  public void ReadCallback(IAsyncResult ar)
  {
  String content = String.Empty;
  // Retrieve the state object and the handler socket 
  // from the asynchronous state object. 
  StateObject state = (StateObject)ar.AsyncState;
  Socket handler = state.workSocket;
  // Read data from the client socket.  
  int bytesRead = handler.EndReceive(ar);
  if (bytesRead > 0)
  {
  // There might be more data, so store the data received so far. 
  state.sb.Append(Encoding.ASCII.GetString(
  state.buffer, 0, bytesRead));
  // Check for end-of-file tag. If it is not there, read  
  // more data. 
  content = state.sb.ToString();

  //检查报文长度
  if (content.Length > 0)
  {
  MessageBox.Show("收到消息:"+content);
  //this.textBox1.Text += content;
  }

  else
  {
  // Not all data received. Get more. 
  handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  new AsyncCallback(ReadCallback), state);
  }
  }
  }
   

客户端处理函数,连接服务器,向服务器发送报文,每次发送完报文后,必须重新连接,才能发送报文:
  /// <summary>
&nb