I've got a program, a board game, that plays over LAN. I used Asynchronous sockets to connect the server and the client, so that the server won't hang until the client responds. The game flow would be like this:

Player A starts server by typing in a Port number
Player B connects to the server by typing in host IP and Port number
Player A receives a "Player B connected", and must send some settings back.
Player B receives settings from Player A (location of player, as well as who goes first)
One of the player goes first. The other follows.
At any time, players can chat with each other.

Now, I got the connection part right. The client even sends a "Player Name connected" message. But because I based my code on a Asynchronous Chat application, I'm not sure how to proceed, or rather, how I can get my server to send some settings (mostly just ints) that the client will read as settings, instead of a message.

So, basically, I'm asking for some logical help here. Do I make another function similar to the one sending messages, but sends integers instead? Or will that mess with the connection, since the client is expecting a message? Or something else will go wrong?

I'm just a beginner in socket programming. Thanks in advance for all those who will reply, and sorry if it is a bit long. I will post the codes if necessary / on demand.

Here is the code for the server:

delegate void FixCallBack(IAsyncResult asyn);
public AsyncCallback pfnWorkerCallBack;
public Socket m_socListener;
public Socket m_socWorker;

 public class CSocketPacket
        {
            public System.Net.Sockets.Socket thisSocket;
            public byte[] dataBuffer = new byte[1];
        }

public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                if (this.InvokeRequired)
                {
                    FixCallBack dd = new FixCallBack(OnDataReceived);
                    this.Invoke(dd, new object[] { asyn });
                }
                else
                {
                    CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
                    //end receive...
                    int iRx = 0;
                    iRx = theSockId.thisSocket.EndReceive(asyn);
                    char[] chars = new char[iRx + 1];
                    System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                    int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
                    System.String szData = new System.String(chars);

                    lblStatMsgInvi.Text = lblStatMsgInvi.Text + szData.ToString();

                    lblStatmsg.Text = lblStatMsgInvi.Text;
                    WaitForData(m_socWorker);
                }
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                m_socWorker = m_socListener.EndAccept(asyn);

                WaitForData(m_socWorker);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }
                CSocketPacket theSocPkt = new CSocketPacket();
                theSocPkt.thisSocket = soc;
                // now start to listen for any data...
                soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

private void btnCreate_Click(object sender, EventArgs e)
        {
            int port = 0;            
            pnlSubLobby.Visible = true;
            txtPort.Enabled = false;
            chkIPv4.Enabled = false;
            btnCreate.Enabled = false;

            if (txtPort.Text.Length > 0)
            {
                try
                {
                    port = int.Parse(txtPort.Text);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "GG");
                }
            }
            else
            {
                if (MessageBox.Show("Would you like to open a random port?", "GG", MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.Yes))
                {
                    port = 8888;
                }
                else if (MessageBox.Show("Would you like to open a random port?", "GG", MessageBoxButtons.YesNo, MessageBoxIcon.Question).Equals(DialogResult.No))
                {
                    MessageBox.Show("A port number must be specified.", "GG");
                }
            }

            try
            {
                //create the listening socket...
                m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse(lblIpAd.Text), int.Parse(txtPort.Text));
                //bind to local IP Address...
                m_socListener.Bind(ipLocal);
                //start listening...
                m_socListener.Listen(4);
                // create the call back for any client connections...
                m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

private void btnSendData_Click(object sender, System.EventArgs e)
		{
			try
			{
				Object objData = txtDataTx.Text;
				byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
				m_socWorker.Send (byData);
			}
			catch(SocketException se)
			{
				MessageBox.Show (se.Message );
			}
		}

First the user clicks the btnCreate, which starts a server and listens for incoming connections. Above we also have some functions that receive data, something for when a client connects, as well as something for waiting for data.

I assume that I need to copy and modify some of this functions (the on data received, the send data, and the wait for data) to allow the server to receive a different type of data, but I'm not sure if that's a wise thing to do. Any advise / comments / suggestions?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.