Here is my code.
class RowaReceiver { /// <summary> /// define socket variables /// </summary> public class StateObject { public Socket workSocket = null; public byte[] buffer = new byte[BufferSize]; public StringBuilder sb = new StringBuilder(); } public const int BufferSize = 1024; //declare socket variable /// <summary> /// asynchronously listen socket /// </summary> public class AsynchronousSocketListner { public static ManualResetEvent allDone = new ManualResetEvent(false); public AsynchronousSocketListner() { } /// <summary> /// start socket listening /// </summary> public static void StartListening() { byte[] bytes = new Byte[1024]; IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 1024); Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { listener.Bind(localEndpoint); listener.Listen(10); while (true) { allDone.Reset(); //Waiting for a connection listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); allDone.WaitOne(); } } catch (Exception ex) { //exception message } } public static void AcceptCallback(IAsyncResult ar) { allDone.Set(); Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), state); } public static void ReadCallback(IAsyncResult ar) { if (ar.IsCompleted) { string content = string.Empty; StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; int bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { state.sb.Append(Encoding.ASCII.GetString( state.buffer, 0, bytesRead)); //get socket from Rowa content = state.sb.ToString(); Send(handler, content); } } } private static void Send(Socket handler, String data) { byte[] byteData = Encoding.ASCII.GetBytes(data); handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler); } private static void SendCallback(IAsyncResult ar) { try { Socket handler = (Socket)ar.AsyncState; int bytesSent = handler.EndSend(ar); handler.Shutdown(SocketShutdown.Both); handler.Close(); } catch (Exception e) { //Exception message } } } }
This code snippet can successfully receive and send packet onto my simulator. But, sometimes, I only need to send packet, my question is "how can I seperate the above code snippet and let Send module seperately, and then I can call Send method in other class files."
Thanks,