0 Replies - 627 Views - Last Post: 19 October 2017 - 01:43 PM

#1 VIPERHlr  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 111
  • Joined: 05-August 11

Getting server to send data to second client

Posted 19 October 2017 - 01:43 PM

Hi, I have setup a multi-threaded tcp server. So basically this server acts as the intermediary between the data transfer of two clients. The two clients connect to the server and I want that whatever data is sent to the server by one client is sent to the second client. Here is the code I worked on so far

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace server2
{
    class Program
    {
        private static Boolean _isRunning;
        private static TcpListener _server;

        static void Main(string[] args)
        {

            try
            {
                _server = new TcpListener(IPAddress.Any, 55635);
                _server.Start();
                Console.WriteLine("Server started");
                _isRunning = true;
                LoopClients();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.Read();
            }
        }

        private static void LoopClients()
        {
            while (_isRunning==true)
            {
                // wait for client connection
                TcpClient newClient = _server.AcceptTcpClient();
                Console.WriteLine("New client connected");

                // client found.
                // create a thread to handle communication
                Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
                t.Start(newClient);
            }
        }

        private static void HandleClient(object obj)
        {
            TcpClient client = (TcpClient)obj;

            byte[] recievedBuffer = new byte[100];
            NetworkStream stream = client.GetStream();

            while(client.Connected==true)
            {
                stream.Read(recievedBuffer, 0, recievedBuffer.Length);

                StringBuilder msg = new StringBuilder();
                
                foreach(byte b in recievedBuffer)
                {
                    if (b.Equals(00))
                    {
                        break;
                    }
                    else
                        msg.Append(Convert.ToChar(B)/>.ToString());
                }
                Console.WriteLine(msg.ToString() + msg.Length); 
            }
            Console.WriteLine("Client disconnected");
        }
    }
}


How to go about doing that ?, thanks

Is This A Good Question/Topic? 0
  • +

Page 1 of 1