SalataLuc
SalataLuc

Reputation: 410

Send data from server back to the client

I have a TcpClient application that send a message from client to the server. Code below:

clsServer.cs

public void server_start()
    {
        this.tcpListener = new TcpListener(new IPAddress(new Byte[] { 172, 16, 1, 55 }), 9999);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));

        _rtb_Input.AppendText("Listening... Press any key to stop" + System.Environment.NewLine);
        this.listenThread.Start();
    }

    private void ListenForClients()
    {
        this.tcpListener.Start();
        while (true)
        {
            //blocks until a client has connected to the server
            client = this.tcpListener.AcceptTcpClient();

            //create a thread to handle communication
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }

    public event MessageReceivedHandler MessageReceived;
    private void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

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

        while (true)
        {
            bytesRead = clientStream.Read(message, 0, 4096);

            //message has successfully been received
            ASCIIEncoding encoder = new ASCIIEncoding();
            string msg = encoder.GetString(message, 0, bytesRead);
            if (this.MessageReceived != null)
            {
                this.MessageReceived(msg);
            }
            //send message back select the message from the db
            byte[] buffer = encoder.GetBytes("Hello Client!");

            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();
        }
        tcpClient.Close();
    }

frmClient.cs

public frmClient()
    {
        InitializeComponent();         
    }

    private void btn_ClientStart_Click(object sender, EventArgs e)
    {
        TcpClient client = new TcpClient();

        IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("172.16.1.55"), 9999);
        try
        {
            client.Connect(serverEndPoint);
            NetworkStream clientStream = client.GetStream();

            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] buffer = encoder.GetBytes(rtb_Outpot.Text);

            clientStream.Write(buffer, 0, buffer.Length);
            clientStream.Flush();
        }
        catch (Exception ex)
        {
            rtb_Outpot.AppendText(System.Environment.NewLine + "Failed To Connect to the Server" + System.Environment.NewLine);
        }
    }

frmServer.cs

private void btn_ServerStart_Click(object sender, EventArgs e)
    {
        btn_ServerStop.Enabled = true;
        btn_ServerStart.Enabled = false;
        server = new clsServer(rtb_Input);
        server.MessageReceived += new MessageReceivedHandler(Message_Received);
        server.server_start();
    }

    private void Message_Received(string message)
    {
        //update the display using invoke
        Invoke(new MessageReceivedHandler(PrintToScreen), new object[] { message });
    }

    private void PrintToScreen(string msg)
    {
        msg_counter++;
        rtb_Input.AppendText("msg no': " + msg_counter + System.Environment.NewLine + msg + System.Environment.NewLine);
    }

Works fine, when I send a message from client to the server. But now I can figure out a way to send data from server back to the client. Will I have to make a thread for the client form too?

Thanks.

Upvotes: 1

Views: 4810

Answers (1)

M.Babcock
M.Babcock

Reputation: 18965

The code posted looks more like you're trying to find a way to receive the message sent from the server. The code in clsServer.cs already contains the code necessary to send data to the client.

Your client code is just missing the necessary calls to read the response from clientStream. How that is implemented in your application will vary depending on your requirements. Personally, I'd probably offload the reading to another thread.

Upvotes: 1

Related Questions