Created
May 7, 2012 00:08
-
-
Save micahasmith/2625087 to your computer and use it in GitHub Desktop.
simple c# tcp server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| using System.Net.Sockets; | |
| using System.Data; | |
| using System.Net; | |
| using System.Threading; | |
| using System.Threading.Tasks; | |
| namespace RxWeb | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var server = Task.Factory.StartNew(() => | |
| { | |
| try | |
| { | |
| NetActor a = new NetActor(8081,(s)=>Console.Write(s)); | |
| } | |
| catch (Exception exc) | |
| { | |
| throw; | |
| } | |
| }); | |
| while (true) | |
| { | |
| ; | |
| } | |
| } | |
| } | |
| public class NetActor | |
| { | |
| Socket _Listener; | |
| public NetActor(int port,Action<string> onRead) | |
| { | |
| _OnRead = onRead; | |
| _Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
| _Listener.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port)); | |
| _Listener.Listen(20); | |
| _Listener.BeginAccept((o)=>BeginAccept(o),_Listener); | |
| } | |
| private Action<string> _OnRead { get; set; } | |
| private void BeginAccept(IAsyncResult ar) | |
| { | |
| var listener = (Socket)ar.AsyncState; | |
| var state=new StateObject() | |
| { | |
| workSocket=_Listener.EndAccept(ar) | |
| }; | |
| state.workSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(BeginRead), state); | |
| } | |
| private void BeginRead(IAsyncResult ar) | |
| { | |
| var state = (StateObject)ar.AsyncState; | |
| int bytes = state.workSocket.EndReceive(ar); | |
| if (bytes > 0) | |
| { | |
| _OnRead(Encoding.ASCII.GetString(state.buffer, 0, bytes)); | |
| //var content = state.sb.ToString(); | |
| //if (content.IndexOf("<EOF>") != -1) | |
| //{ | |
| //} | |
| } | |
| else | |
| { | |
| state.workSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(BeginRead), state); | |
| } | |
| } | |
| private void GetRecieved() { } | |
| // State object for reading client data asynchronously | |
| private 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(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment