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

关于socket异步的问题
根据MSDN上的例子改过,代码如下:

SocketListener.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace PDAserver
{
  public class StateObject
  {
  // Client socket.
  public Socket workSocket = null;
  // Size of receive buffer.
  public const int BufferSize = 1024;
  // Receive buffer.
  public byte[] buffer = new byte[BufferSize];
  // Received data string.
  public StringBuilder sb = new StringBuilder();
  }

  public class SocketListener
  {
  // Thread signal.
  public static ManualResetEvent allDone = new ManualResetEvent(false);
  public String content;

  public SocketListener()
  {
  }

  public void StartListening()
  {
  // Data buffer for incoming data.
  byte[] bytes = new Byte[1024];
  //
  IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
  IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 18600);

  // Create a TCP/IP socket.
  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(localEndPoint);
  listener.Listen(100);

  while (true)
  {
  // Set the event to nonsignaled state.
  allDone.Reset();

  // Start an asynchronous socket to listen for connections.
  Console.WriteLine("Waiting for a connection...");
  listener.BeginAccept(
  new AsyncCallback(AcceptCallback),
  listener);

  // Wait until a connection is made before continuing.
  allDone.WaitOne();
  }

  }
  catch (Exception e)
  {
  Console.WriteLine(e.ToString());
  }

  Console.WriteLine("\nPress ENTER to continue...");
  Console.Read();

  }

  public void AcceptCallback(IAsyncResult ar)
  {
  // Signal the main thread to continue.
  allDone.Set();

  // Get the socket that handles the client request.
  Socket listener = (Socket)ar.AsyncState;
  Socket handler = listener.EndAccept(ar);

  // Create the state object.
  StateObject state = new StateObject();
  state.workSocket = handler;
  handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
  new AsyncCallback(ReadCallback), state);
  }

  public void ReadCallback(IAsyncResult ar)
  {
  //cont