首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

socket 异步通信有关问题,请问!每次发送消息前都要进行重新连接

2012-06-14 
socket 异步通信问题,请教!每次发送消息前都要进行重新连接服务器端代码:///监听private void listen(){//

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>
  /// 连接服务器
  /// </summary>
  public void connectSev()


  {
  ClientThread = new Thread(new ThreadStart(StartClient));
  ClientThread.Start();
  }

  public void StartClient()
  {
  // Connect to a remote device. 
  try
  {
  // Create a TCP/IP socket. 
  Sockclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  // Connect to the remote endpoint. 
  Sockclient.BeginConnect(remoteipe, new AsyncCallback(ConnectCallback), Sockclient);
   
  }
  catch (Exception e)
  {
  MessageBox.Show(e.Message);
  }
  }
  /// <summary>
  /// 连接回调函数
  /// </summary>
  /// <param name="ar"></param>
  private void ConnectCallback(IAsyncResult ar)
  {
  try
  {
  // Retrieve the socket from the state object. 
  Socket client = (Socket)ar.AsyncState;
  // Complete the connection. 
  client.EndConnect(ar);
  Console.WriteLine("Socket connected to {0}",
  client.RemoteEndPoint.ToString());
  // Signal that the connection has been made. 
  connectDone.Set();
  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }
  }
  /// <summary>
  /// 发送报文
  /// </summary>
  /// <param name="client"></param>
  /// <param name="data"></param>
  public void ClientSend(Socket client, String data)
  {
  // Convert the string data to byte data using ASCII encoding. 
  byte[] byteData = Encoding.ASCII.GetBytes(data);
  // Begin sending the data to the remote device. 
  client.BeginSend(byteData, 0, byteData.Length, 0,
  new AsyncCallback(Client_SendCallback), client);
  }
  /// <summary>
  /// 发送回调方式
  /// </summary>
  /// <param name="ar"></param>
  private static void Client_SendCallback(IAsyncResult ar)
  {
  try
  {
  // Retrieve the socket from the state object. 
  Socket client = (Socket)ar.AsyncState;
  // Complete sending the data to the remote device. 
  int bytesSent = client.EndSend(ar);
  Console.WriteLine("Sent {0} bytes to server.", bytesSent);
  // Signal that all bytes have been sent. 
  sendDone.Set();
  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }
  }


[解决办法]
URL先记下,明天有空看下
[解决办法]
应该是不会的啊,stocket应该是一直保持连接的,除非你自己写了关闭连接的代码。或者是你每次连接前都new了一个新的连接

热点排行