fwsteal

fwsteal


  • Name: [not set]
  • Favorite Languages: [not set]
  • Website: [not set]
  • Location: [not set]
  • About Me: [not set]

Recent Comments

  • C# Tutorial - Simple Threaded TCP Server
    08/04/2010 - 11:41

    i read the article and seems good; have a question about getting the data back from the server. How do i do that?

    I have two code files below:

    client form -- windows form with a textbx for remote ip address and port; button for connect to device; status txtbox based on connection; message txtbx to send to remote sever; send button; message received txtbox.

    client.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Collections;
    using System.Threading;
    using System.Net;
    using System.Net.Sockets;
    using System.IO;
    using System.Net.NetworkInformation;

    namespace TCPServerTutorial
    {
        public partial class Client : Form
        {
            IPAddress ip;
            const int port = 1234;
            string myIP = string.Empty;
            string strMode = string.Empty;
            string strAddress = string.Empty;

            TcpClient client = new TcpClient();
            Server server = new Server();

            public Client()
            {
                InitializeComponent();
                txtbxIPAddress.Text = "192.168.10.147";
                txtbxPort.Text = "1234";
            }

            private void txtbxConnectToDevice_Click(object sender, EventArgs e)
            {
                //get the remote IP address
                IPAddress address = IPAddress.Parse(txtbxIPAddress.Text.Trim());
                int port = System.Convert.ToInt16(txtbxPort.Text.Trim());

                //create the end point
                IPEndPoint serverEndPoint = new IPEndPoint(address, port);

                client.Connect(serverEndPoint); //connect to server

                if (this.client.Connected)
                {
                    txtbxConnectionStatus.Text = "Connected";
                }
                else
                {
                    txtbxConnectionStatus.Text = "Not Connected";
                }
            }

            private void btnSendMessage_Click(object sender, EventArgs e)
            {
                NetworkStream clientStream = client.GetStream();

                ASCIIEncoding encoder = new ASCIIEncoding();
                string text = txtbxMessageToSend.Text.Trim();

                byte[] buffer = encoder.GetBytes(text); //send a message

                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();

                server.MessageReceived += new Server.MessageReceivedHandler(Message_Received);

            }

            void Message_Received(string message)
            {
                //update the display using invoke
                txtbxMessageReceived.Text = message.ToString();
            }

            private void btnExit_Click(object sender, EventArgs e)
            {
                client.Close();
                Application.Exit();
            }
        }
    }

    server.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;

    namespace TCPServerTutorial
    {
        class Server
        {
            //a simple threaded server that accepts connections and read data from clients.
            private TcpListener tcpListener; //wrapping up the underlying socket communication
            private Thread listenThread; //listening for client connections
            const int iPort = 3000; //server port

            public Server()
            {
                this.tcpListener = new TcpListener(IPAddress.Any, iPort);
                this.listenThread = new Thread(new ThreadStart(ListenForClients));
                this.listenThread.Start();
            }

            private void ListenForClients()
            {
                this.tcpListener.Start(); //start tcplistener

                //sit in a loop accepting connections
                while (true)
                {
                    //block until a client has connected to the server
                    TcpClient client = this.tcpListener.AcceptTcpClient();

                    //when connected - create a thread to handle communication with a connected client
                    Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                    //pass the tcpclient object returned by the accepttcpclient call to our new thread
                    clientThread.Start(client);
                }
            }

            private void HandleClientComm(object client)
            {
                TcpClient tcpClient = (TcpClient)client; //cast client as a tcpclient object
                //because the parameterizedthreadstart delegate can only accept object types.

                //get the network stream from the tcpclient - used for reading
                NetworkStream clientStream = tcpClient.GetStream();

                byte[] message = new byte[4096];
                int bytesRead;

                //sit in a true loop reading information from the client
                while (true)
                {
                    bytesRead = 0;

                    try
                    {
                        //block until a client sends a message and is received
                        bytesRead = clientStream.Read(message, 0, 4096);
                    }
                    catch (Exception ex)
                    {
                        //a socket error has occurred
                        throw ex;
                        //MessageBox.Show(ex.Message);
                        //break;
                    }

                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the server
                        //MessageBox.Show("The client has disconnected from the server.");
                        break;
                    }

                    //message has successfully been recieved
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    string smessage = encoder.GetString(message, 0, bytesRead);
                    if (this.MessageReceived != null)
                        this.MessageReceived(smessage);

                    //System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
                    //MessageBox.Show(encoder.GetString(message, 0, bytesRead));


                    //send data back to client
                    //use the tcpclient object to send data back to client
                    //byte[] buffer = encoder.GetBytes("Hello");
                    //clientStream.Write(buffer, 0, buffer.Length);
                    //clientStream.Flush();
                }

                //close
                tcpClient.Close();
            }

            public event MessageReceivedHandler MessageReceived;

            public delegate void MessageReceivedHandler(string message);
        }
    }

    Any help would be great. Thank you.