Just small and super simple code that shows basic setup for asynchronous server. Tho please note that it is an example and you would have to edit it to actually read the data from packet and then implement send methods, as well as disconnect methods to properly close socket and remove connection.
jM2Server.cs
Code:using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; namespace jM2MonoServerTest001 { public class jM2Server { private Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private List<jM2Connection> serverConnections = new List<jM2Connection>(); public jM2Server (string serverIp, int serverPort) { serverSocket.Bind(new IPEndPoint(IPAddress.Parse(serverIp), serverPort)); serverSocket.Listen(4); serverSocket.BeginAccept(new AsyncCallback(OnAccept), null); } private void OnAccept(IAsyncResult iar) { serverConnections.Add(new jM2Connection(serverSocket.EndAccept(iar), this)); serverSocket.BeginAccept(new AsyncCallback(OnAccept), null); } } }
jM2Connection.cs
If this is useless I can delete the thread, I don't mind. When I was looking into C# Asynchronous Server I was looking for something like this, clean, and simple. Tho learned hard way from emulators lol.Code:using System; using System.Net; using System.Net.Sockets; namespace jM2MonoServerTest001 { public class jM2Connection { private Socket connectionSocket; private jM2Server connectionServer; private byte[] connectionBuffer = new byte[2048]; public jM2Connection (Socket socket, jM2Server server) { connectionSocket = socket; connectionServer = server; connectionSocket.BeginReceive(connectionBuffer, 0, connectionBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } private void OnReceive(IAsyncResult iar) { int bytesReceived = connectionSocket.EndReceive(iar); if (bytesReceived > 0) { // data received, it's length is stored in bytesReceived and data itself is in connection buffer connectionSocket.BeginReceive(connectionBuffer, 0, connectionBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } else { // client disconnected probably } } } }
P.S. If anyone interested I can post a more updated/full code where I have packet class for reading and writing packets as well as log class plus other.


Reply With Quote![[C#]Basic Asynchronous Server](http://ragezone.com/hyper728.png)

