Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello Everyone at CodeProject , as title say i am editing an Online Game Server Socket to make it for the same game but as a client socket , actually i tried it many times but fails , spent more time on that , well ,, here is my idea..

Server and client each one have 2 sockets... Login Socket , Game Socket

Server socket working very well , but i need to edit it to work with the client , just receiving and sending data , bytes and packets.. and don`t listen for incoming connections ... as i said i spent long time on this i got it worked successfully , but not as i am looking for ...

i want it sending and receiving at same time as Server Socket doing ...

here is Socket Files ...

So what edits can be done in this files to make it as i explained ?

C#
public class WinSocket
    {
        private Socket Connection;
        private bool disconnected = false;
        public bool Disabled = false;
        public WinSocket()
        {
            Connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
        public WinSocket(Socket socket)
        {
            Connection = socket;
        }

        public void Bind(EndPoint point)
        {
            if (disconnected) return;
            Connection.Bind(point);
        }
        public void Listen(int backlog)
        {
            if (disconnected) return;
            Connection.Listen(backlog);
        }
        public void BeginAccept(AsyncCallback async, object state)
        {
            if (Disabled) return;
            try
            {
                if (disconnected) return;
                Connection.BeginAccept(async, state);
            }
            catch
            {
                Disabled = true;
            }
        }
        public void BeginReceive(byte[] buffer, int offset, int size, SocketFlags flag, AsyncCallback callback, object state)
        {
            if (Disabled) return;
            try
            {
                if (disconnected || !Connected) return;
                Connection.BeginReceive(buffer, offset, size, flag, callback, state);
            }
            catch
            {
                Disabled = true;
            }
        }
        public int EndReceive(IAsyncResult res, out SocketError err)
        {
            err = SocketError.Disconnecting;
            if (Disabled) return 0;
            try
            {
                if (!Usable) return 0;
                return Connection.EndReceive(res, out err);
            }
            catch
            {
                Disabled = true;
            }
            return 0;
        }
        public Socket EndAccept(IAsyncResult async)
        {
            if (Disabled) return null;
            try
            {
                if (disconnected) return null;
                return Connection.EndAccept(async);
            }
            catch
            {
                Disabled = true;
            }
            return null;
        }
        public Socket Accept()
        {
            if (Disabled) return null;
            try
            {
                if (disconnected) return null;
                return Connection.Accept();
            }
            catch
            {
                Disabled = true;
            }
            return null;
        }
        public void Close()
        {
            //Connection.Close();
        }
        public void Send(byte[] buffer)
        {
            if (Disabled) return;
            try
            {
                if (disconnected) return;
                Connection.Send(buffer);
            }
            catch
            {
                Disabled = true;
            }
        }
        public void Disconnect(bool reuse)
        {
            if (Disabled) return;
            try
            {
                if (!disconnected)
                    disconnected = true;
                else
                    return;
                Connection.Disconnect(reuse);
            }
            catch
            {
                Disabled = true;
            }
        }
        public void Shutdown(SocketShutdown type)
        {
            //Connection.Shutdown(type);
        }
        public bool Connected
        {
            get
            {
                if (Disabled) return false;
                try
                {
                    if (disconnected) return false;
                    return Connection.Connected;
                }
                catch
                {
                    Disabled = true;
                }
                return false;
            }
        }
        public int Receive(byte[] buffer)
        {
            if (disconnected) return 0;
            return Connection.Receive(buffer);
        }
        public EndPoint RemoteEndPoint
        {
            get
            {
                if (Disabled) return new IPEndPoint(1, 1);
                try
                {
                    return Connection.RemoteEndPoint;
                }
                catch
                {
                    Disabled = true;
                }
                return new IPEndPoint(1, 1);
            }
        }
        private bool Usable
        {
            get
            {
                return !disconnected;
            }
        }
        public void Disable()
        {
            try
            {
                Disabled = true;
                Connection.Close();
            }
            catch
            {
                Disabled = true;
            }
        }
    }


C#
public class SyncSocketWrapper : Interfaces.ISocketWrapper
    {
        public int BufferSize
        {
            get;
            set;
        }
        public byte[] Buffer
        {
            get;
            set;
        }
        public WinSocket Socket
        {
            get;
            set;
        }
        public object Connector
        {
            get;
            set;
        }
        public Interfaces.ISocketWrapper Create(Socket socket)
        {
            BufferSize = 8000;
            Socket = new WinSocket(socket);
            Buffer = new byte[BufferSize];
            return this;
        }

        private Thread thread;

        private SyncSocket Server;

        public void BeginReceive(SyncSocket server)
        {
            Server = server;
            thread = new Thread(new ThreadStart(Receive));
            thread.Start();
        }

        private void Receive()
        {
            try
            {
                while (Socket.Connected)
                {
                    try
                    {
                        int RecvSize = Socket.Receive(Buffer);
                        if (RecvSize > 0)
                        {
                            byte[] buffer = new byte[RecvSize];
                            for (int i = 0; i < RecvSize; i++)
                            {
                                buffer[i] = Buffer[i];
                            }
                            Server.InvokeOnClientReceive(this, buffer);
                        }
                        else
                        {
                            Server.InvokeDisconnect(this);
                            return;
                        }
                    }
                    catch (SocketException)
                    {
                        Server.InvokeDisconnect(this);
                        return;
                    }
                    catch (ObjectDisposedException)
                    {
                        Server.InvokeDisconnect(this);
                        return;
                    }
                    catch (Exception e) { MessageBox.Show(e.Message); }
                }
                Server.InvokeDisconnect(this);
                return;
            }
            catch (ThreadAbortException)
            {
                Server.InvokeDisconnect(this);
                return;
            }
        }
    }


C#
public class SyncSocket
    {
        private WinSocket Connection = new WinSocket();
        private bool enabled;
        public event Action<Interfaces.ISocketWrapper> OnClientConnect;
        public event Action<Interfaces.ISocketWrapper> OnClientDisconnect;
        public event Action<byte[], Interfaces.ISocketWrapper> OnClientReceive;
        private ushort port;
        private Thread mainThread;

        public SyncSocket(ushort port)
        {
            if (!this.enabled)
            {
                this.port = port;
                this.Connection.Bind(new IPEndPoint(IPAddress.Any, this.port));
                this.Connection.Listen(10);
                this.enabled = true;
                mainThread = new Thread(new ThreadStart(this.SyncConnect));
                mainThread.Start();
            }
        }

        private void SyncConnect()
        {
            try
            {
                while (true)
                {
                    if (Connection.Disabled)
                        return;
                    if (!this.enabled)
                        return;
                    SyncSocketWrapper sender = null;
                    try
                    {
                        sender = new SyncSocketWrapper();
                        sender.Create(this.Connection.Accept());
                        if (this.OnClientConnect != null)
                        {
                            this.OnClientConnect(sender);
                        }
                        sender.BeginReceive(this);
                    }
                    catch (SocketException e)
                    {
                        MessageBox.Show(e.Message);

                    }
                    catch (ObjectDisposedException e)
                    {
                        MessageBox.Show(e.Message);
                    }
                    catch (Exception e) { MessageBox.Show(e.Message); }
                }
            }
            catch (ThreadAbortException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        public void InvokeOnClientConnect(SyncSocketWrapper sender)
        {
            if (this.OnClientConnect != null)
            {
                this.OnClientConnect(sender);
            }
        }

        public void InvokeOnClientReceive(SyncSocketWrapper sender, byte[] buffer)
        {
            if (this.OnClientReceive != null)
            {
                this.OnClientReceive(buffer, sender);
            }
        }

        public void Disable()
        {
            if (this.enabled)
            {
                this.Connection.Disable();
                this.enabled = false;
            }
        }

        public void Enable()
        {
            if (!this.enabled)
            {
                this.Connection.Bind(new IPEndPoint(IPAddress.Any, this.port));
                this.Connection.Listen(100);
                this.enabled = true;
                if (mainThread != null)
                {
                    mainThread.Abort();
                    mainThread = null;
                }
                mainThread = new Thread(new ThreadStart(this.SyncConnect));
                mainThread.Start();
            }
        }

        private void enabledCheck(string Variable)
        {
            if (this.enabled)
            {
                throw new Exception("Cannot modify " + Variable + " while socket is enabled.");
            }
        }

        public void InvokeDisconnect(SyncSocketWrapper Client)
        {
            if (Client != null)
            {
                try
                {
                    if (Client.Socket.Connected)
                    {
                        Client.Socket.Disconnect(false);
                        Client.Socket.Shutdown(SocketShutdown.Both);
                        Client.Socket.Close();
                        if (this.OnClientDisconnect != null)
                            this.OnClientDisconnect(Client);
                        Client.Connector = null;
                        Client = null;
                    }
                    else
                    {
                        Client.Socket.Shutdown(SocketShutdown.Both);
                        Client.Socket.Close();
                        if (this.OnClientDisconnect != null)
                            this.OnClientDisconnect(Client);

                        Client.Connector = null;
                        Client = null;
                    }
                }
                catch (ObjectDisposedException e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

        public bool Enabled
        {
            get
            {
                return this.enabled;
            }
        }

        public ushort Port
        {
            get
            {
                return this.port;
            }
            set
            {
                this.enabledCheck("Port");
                this.port = value;
            }
        }
    }




C#
public class AsyncSocketWrapper : Interfaces.ISocketWrapper
    {
        public int BufferSize
        {
            get;
            set;
        }
        public byte[] Buffer
        {
            get;
            set;
        }
        public WinSocket Socket
        {
            get;
            set;
        }
        public object Connector
        {
            get;
            set;
        }
        public Interfaces.ISocketWrapper Create(Socket socket)
        {
            BufferSize = 8000;
            Socket = new WinSocket(socket);
            Buffer = new byte[BufferSize];
            return this;
        }
    }




C#
public class AsyncSocket
    {
        private int backlog;
        private int clientbuffersize = 0xffff;
        private WinSocket Connection = new WinSocket();
        private bool enabled;
        public bool GameServer = false;
        public event Action<Interfaces.ISocketWrapper> OnClientConnect;
        public event Action<Interfaces.ISocketWrapper> OnClientDisconnect;
        public event Action<byte[], Interfaces.ISocketWrapper> OnClientReceive;
        private ushort port;

        public AsyncSocket(ushort port)
        {
            if (!this.enabled)
            {
                this.port = port;
                this.Connection.Bind(new IPEndPoint(IPAddress.Any, this.port));
                this.Connection.Listen(100);
                this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
                this.enabled = true;
            }
        }
        
        private void AsyncConnect(IAsyncResult res)
        {
            AsyncSocketWrapper sender = null;
            try
            {
                sender = new AsyncSocketWrapper();
                sender.Create(this.Connection.EndAccept(res));
                if (sender.Socket == null)
                {
                    this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);

                    return;
                }
                if (this.OnClientConnect != null)
                {
                    this.OnClientConnect(sender);
                }
                sender.Socket.BeginReceive(sender.Buffer, 0, sender.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), sender);

                this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
            }
            catch (SocketException e)
            {
                MessageBox.Show(e.Message);
                if (this.enabled)
                {
                    this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
                }
            }
            catch (ObjectDisposedException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private unsafe void AsyncReceive(IAsyncResult res)
        {
            bool was = false;
            try
            {
                SocketError error;
                AsyncSocketWrapper asyncState = (AsyncSocketWrapper)res.AsyncState;
                int RecvSize = asyncState.Socket.EndReceive(res, out error);
                if ((error == SocketError.Success) && (RecvSize > 0))
                {
                    was = true;
                    byte[] buffer = new byte[RecvSize];
                    for (int i = 0; i < RecvSize; i++)
                    {
                        buffer[i] = asyncState.Buffer[i];
                    }
                    if (this.OnClientReceive != null)
                    {
                        this.OnClientReceive(buffer, asyncState);
                    }
                    asyncState.Socket.BeginReceive(asyncState.Buffer, 0, asyncState.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), asyncState);
                }
                else
                {
                    this.InvokeDisconnect(asyncState);
                }
            }
            catch (SocketException e)
            {
                MessageBox.Show(e.Message);
            }
            catch (ObjectDisposedException e)
            {
                MessageBox.Show(e.Message);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                if (was)
                {
                    AsyncSocketWrapper asyncState = (AsyncSocketWrapper)res.AsyncState;
                    asyncState.Socket.BeginReceive(asyncState.Buffer, 0, asyncState.Buffer.Length, SocketFlags.None, new AsyncCallback(this.AsyncReceive), asyncState);
                }
            }
        }

        public void Disable()
        {
            if (this.enabled)
            {
                this.Connection.Disable();
                this.enabled = false;
            }
        }

        public void Enable()
        {
            if (!this.enabled)
            {
                this.Connection.Bind(new IPEndPoint(IPAddress.Any, this.port));
                this.Connection.Listen(this.backlog);
                this.Connection.BeginAccept(new AsyncCallback(this.AsyncConnect), null);
                this.enabled = true;
            }
        }

        private void enabledCheck(string Variable)
        {
            if (this.enabled)
            {
                throw new Exception("Cannot modify " + Variable + " while socket is enabled.");
            }
        }

        public void InvokeDisconnect(AsyncSocketWrapper Client)
        {
            if (Client != null)
            {
                try
                {
                    if (Client.Socket.Connected)
                    {
                        Client.Socket.Shutdown(SocketShutdown.Both);
                        Client.Socket.Close();
                        if (this.OnClientDisconnect != null)
                        {
                            this.OnClientDisconnect(Client);
                        }
                        Client.Connector = null;
                        Client = null;
                    }
                    else
                    {
                        if (this.OnClientDisconnect != null)
                        {
                            this.OnClientDisconnect(Client);
                        }
                        Client.Connector = null;
                        Client = null;
                    }
                }
                catch (ObjectDisposedException e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }

        public int Backlog
        {
            get
            {
                return this.backlog;
            }
            set
            {
                this.enabledCheck("Backlog");
                this.backlog = value;
            }
        }

        public int ClientBufferSize
        {
            get
            {
                return this.clientbuffersize;
            }
            set
            {
                this.enabledCheck("ClientBufferSize");
                this.clientbuffersize = value;
            }
        }

        public bool Enabled
        {
            get
            {
                return this.enabled;
            }
        }

        public ushort Port
        {
            get
            {
                return this.port;
            }
            set
            {
                this.enabledCheck("Port");
                this.port = value;
            }
        }
    }


C#
public interface ISocketWrapper
    {
        int BufferSize { get; set; }
        byte[] Buffer { get; set; }
        WinSocket Socket { get; set; }
        object Connector { get; set; }
        ISocketWrapper Create(System.Net.Sockets.Socket socket);
    }
Posted

1 solution

I think you should have a look at this:

Reusable multithreaded TCP client and server classes with example project in VB.NET[^]

That will do what you need - two way conversations, appearing to be simultaneous. You won't need a separate socket to log in either.

Yes, it's a VB.NET project, but the tcp/ip classes are wrapped in a .dll, so you'll just need to add a reference to it in your project.

-Pete
 
Share this answer
 
Comments
Ali Al-Masry 18-Apr-14 19:10pm    
i converted it to C# and its run successfully , but still not what i am looking for like the socket i posted above ...
pdoxtader 19-Apr-14 9:41am    
What did you convert? And why? If you downloaded version 3, could could have simply added that .dll to you're project, and not have had to convert anything.

And what do you need to do that this library doesn't? With this library, you can send and receive simultaneously. You can have 250 conversations going over a single port (using channels). You can send and receive a file at the same time while also sending your own text or data, throttle bandwidth at the server, track clients by an id you assign them...

I've already done the work your asking about, and tested it, and hundereds of people have downloaded it, and tested it, and written clients for other operating systems for it...

And it's really simple to use. So I'm confused. What do you need to do in your application that you couldn't do more easily and quickly using that library?

I just had another look at your description here so I can try to better understand what your asking... and it looks to me like you would need to use two channels, using this library. One for your login and commands (text), and one for your byte data. That's a very simple setup, and extremely easy to do with this library.

No one else here is going to write that code for you... good luck.

-Pete

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900