7 Replies - 4686 Views - Last Post: 14 November 2012 - 01:26 PM Rate Topic: -----

#1 codecsmash49  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 61
  • Joined: 09-December 08

Client/Server .net remoting and multithreading

Posted 05 November 2012 - 08:05 AM

I am having a problem when I try to pass information and correctly populate the chat windows with the information.I am trying to have it as to each time an instance of the program is launched a Client and a Server are both started. I establish a HTTP connection between the Client and the server: S1 C1 and S2 C2: C1 talks to S2 and C2 talks to S1 to allow the display of information to be cross between the 2 chat windows.

When I send from C1 to S2 I cannot think(mental block) of how to send from S2 to display on C2 and vice versa. Currently C1 talks to S2 but then displays on C1, I and guessing due to the threading I established when I created the Server. What would be the best way to display information to both C1 and C2 using a multithreading .net remoting connection.

Client Server:
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 ChatRoom;
using RemoteServer;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Threading;
using System.Diagnostics;
using System.Timers;

namespace ClientServerGui
{
    public partial class Form1 : Form
    {
        private Class1 server;
        private Thread thread;
        //private Thread thread2;
        //private HttpChannel ClientHttpChannel;
        private string UserName;
        private RemoteServer.rServer RM;


        public Form1()
        {
            InitializeComponent();
        }

        public static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }


        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ConfigureServer(string port)
        {
            HttpClientChannel ClientChannel = new HttpClientChannel();
            ChannelServices.RegisterChannel(ClientChannel, false);

            RemotingConfiguration.RegisterWellKnownClientType(typeof(Class1), "http://localhost:"
                    + textBoxPort.Text + "/ChatRoom");
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {

            //combine User's name with input text
            string send = UserName + ": " + textBoxSend.Text;
            while( textBoxSend.Text != "")
            {
                //send message
                RM.sendMessage(send);

                //Clear and focus to start new message
                textBoxSend.Clear();
                buttonSend.Focus();
            }

            textBoxChatWindowDisplay.Text += send;
            textBoxChatWindowDisplay.Text = RM.OutputWindow();
            //textBoxChatWindowDisplay.Text += "\n";


            //listBoxUserList.Items.Clear();
            //    foreach (string x in displayUsers)
            //    {
            //        listBoxUserList.Items.Add(displayUsers);                    
            //    }
               
        }

        public void chatReloadTimer_Tick(object sender, EventArgs e)
        {
                      
            textBoxChatWindowDisplay.Text = RM.OutputWindow();
            StartServer();
 
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            //RemoteServer.Form1 port = new RemoteServer.Form1();


            //string Serverport = port.ServerPort(); 

            if (textBoxUserName.Text != "")
            {
                UserName = textBoxUserName.Text;
                //ClientHttpChannel = new HttpChannel();
                //ChannelServices.RegisterChannel(ClientHttpChannel, false);

                if (textBoxPort.Text == "")
                {
                    textBoxPort.Text = "9000";
                }
                //server1
                ConfigureServer(textBoxPort.Text);
                //server2
               // ConfigureServer(Serverport);

                //Call RemoteServer connecting Class
                RM = new RemoteServer.rServer();

                RM.ConnectServer(UserName);

                //server = new Class1();
                //add user  
                //server.addUserName(UserName);
                //server.test();
                //new thread
                thread = new Thread(new ThreadStart(StartServer));
                //start thread
                thread.Start();

                //new thread
                //thread2 = new Thread(new ThreadStart(StartServer2));
                //start thread
                //thread2.Start();

                buttonSend.Focus();

                System.Windows.Forms.Timer chatReloadTimer = new System.Windows.Forms.Timer();
                chatReloadTimer.Interval = (100); // .1 seconds refresh
                chatReloadTimer.Tick += new EventHandler(chatReloadTimer_Tick);
                chatReloadTimer.Start();
            }


        }

        private void StartServer()
        {
            string currentChatWindow;

            //set array list to capture people joining server
            ArrayList usersArrayList = RM.userNamesList();
            
            //** BAD FOR CHATROOM STYLE****
            //if (listBoxUserList.ItemHeight > 0)//if not enmpy kill all
            //{
            //    //empty listbox
            this.Invoke(new MethodInvoker(delegate() { listBoxUserList.Items.Clear(); }));
            //}

            // Add all users to listbox
            //while (usersAL != null)
            //{
            foreach (string x in usersArrayList)
                {
                    //listBoxUserList.Items.Add(UserName);
                    this.Invoke(new MethodInvoker(delegate() { listBoxUserList.Items.Add(x); }));
                }
            //}

            //display data to user
            currentChatWindow = RM.OutputWindow();
            //textBoxChatWindowDisplay.Text = currentChatWindow;
            this.Invoke(new MethodInvoker(delegate() { textBoxChatWindowDisplay.Text = currentChatWindow; }));
            
            //listBoxUserList.Items.Add(
        }

        //private void StartServer2()
        //{
        //    string currentChatWindow;

        //    //set array list to capture people joining server
        //    ArrayList usersArrayList = server.userList();

        //    this.Invoke(new MethodInvoker(delegate() { listBoxUserList.Items.Clear(); }));

        //    // Add all users to listbox
        //    foreach (string x in usersArrayList)
        //    {
        //        this.Invoke(new MethodInvoker(delegate() { listBoxUserList.Items.Add(x); }));
        //    }

        //    //display data to user
        //    currentChatWindow = server.OutputWindow();

        //    this.Invoke(new MethodInvoker(delegate() { textBoxChatWindowDisplay.Text = currentChatWindow; }));
        //}

        private void Form1_Load(object sender, EventArgs e)
        {
            //Boolean on = true;
            Process start = new Process();

            start.StartInfo.FileName = "RemoteServer";
            start.Start();

            MessageBox.Show("Continue?", "Continue", MessageBoxButtons.OKCancel);
            

            //while (on == true)
            //{
            //    Thread.Sleep(1);
            //    textBoxChatWindowDisplay.Text = server.OutputWindow();
            //}
            buttonSend.Focus();
        }     
        
    }
}



ChatRoom Class

using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels.Http;

namespace ChatRoom
{

    public class Class1:MarshalByRefObject
    {
        // initialize Arraylist to store users signed into chat room
        private static ArrayList userNames = new ArrayList();        
        private static string chatWindow; // fuck u, now ye be a static var
        

        

        public void sendMessage(string message)
        {

            if (message != null)
            {                                
                    //add to chat window
                chatWindow += message + Environment.NewLine;                 
            }
        }
        //public void test()
        //{
        //    Console.WriteLine("pizza");
        //}
        public void addUserName(string UserName)
        {
            String test = UserName;
            Console.WriteLine(test);
            userNames.Add(test);
            Console.WriteLine("0");
        }

        public void deleteUserName(string userName)
        {
            if (userName != null)
            {
                userNames.Remove(userName);
            }
        }

        public ArrayList userList()
        {
            return userNames; // userNames
        }
        public string OutputWindow()
        {
            return chatWindow;
        }
        
    }
}




Server Chat

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.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using ChatRoom;
using System.Runtime.Remoting.Channels.Http;
using RemoteServer;
using System.Threading;
using System.Collections;

namespace RemoteServer
{
    public partial class Form1 : Form
    {
        private int channelNum;
        private static string temp;
        
        public Form1()
        {
            InitializeComponent();
        }

        private void buttonConfirm_Click(object sender, EventArgs e)
        {
            
            temp = textBoxPort.Text;
            channelNum = Convert.ToInt32(temp);

            HttpChannel ServerChannel = new HttpChannel(channelNum);
            Console.WriteLine("httpChannel Set");

            this.Close(); // close GUI
            
            ChannelServices.RegisterChannel(ServerChannel, false);
            Console.WriteLine("channel registered");

            RemotingConfiguration.RegisterWellKnownServiceType(typeof(Class1), "ChatRoom",
                WellKnownObjectMode.SingleCall);
            Console.WriteLine("working");
            Console.WriteLine("Port number is " + channelNum);
            Console.ReadKey();
                        
            
        } 
    }

    public class rServer: MarshalByRefObject
    {
        private Class1 server = new Class1();
        private Thread thread;
        private static string chatWindow;
        private static ArrayList UsersArrayList;

        public void ConnectServer(string UserName)
        {
            server.addUserName(UserName);
        }

        public ArrayList userNamesList()
        {
            UsersArrayList = server.userList();

            return UsersArrayList;
        }
        public string OutputWindow()
        {

            string chatWindow = server.OutputWindow();
            //Console.WriteLine(chatwindow);
            return chatWindow;
        }

        public void sendMessage(string message)
        {

            server.sendMessage(message);
        }
    }
}




Is This A Good Question/Topic? 0
  • +

Replies To: Client/Server .net remoting and multithreading

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,649
  • Joined: 02-June 10

Re: Client/Server .net remoting and multithreading

Posted 05 November 2012 - 08:09 AM

You could continue to re-invent the wheel... Or, we have some great tutorials on making chat systems. As a sidenote: I have no idea why you are trying to launch a client and SERVER every time. Seems you only want one server to handle all the clients.

Chat: FAQ 9
Threading: FAQ 15, 16



tlhIn`toq's FAQ list

Learning to debug one's own code is an essential skill. Sadly, one that apparently few college courses teach. Silly if you ask me.

Placing breakpoints and walking through the code line by line allows you to actually WATCH it execute.

Visualizing what your code does will let you see why it behaves the way it does.

It would be well worth your time to do the tutorials on FAQ 2. A couple hours learning this skill will save you hundreds of hours of confusion in one project alone.


TOP most asked:
What does this error message mean?
FAQ 2: How do I debug
FAQ 3: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated NOV 2012
Spoiler



This post has been edited by tlhIn`toq: 05 November 2012 - 08:11 AM

Was This Post Helpful? 0
  • +
  • -

#3 codecsmash49  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 61
  • Joined: 09-December 08

Re: Client/Server .net remoting and multithreading

Posted 05 November 2012 - 08:33 AM

I had it working as a 1 server multiple client but it was requested a Server and Client is created each time. Makes no sense really. I will check out the tutorials you recommended. I understand that when:
1) C1 hits send it should add its to S1 chat window
2) C1 sends information to S2 and stores it
3) S2 sends information to C2's chat window

I have having the issue of S2 sending information to C2's chat window.

Would it be better to create the chat window in a different class and use it to add Server's information to pass it into it

public string addToChat()
{
       string tempChatStore =  server.chatWindow;
      client chatWindow += tempChatStore + '\n';

}


Was This Post Helpful? 0
  • +
  • -

#4 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,649
  • Joined: 02-June 10

Re: Client/Server .net remoting and multithreading

Posted 05 November 2012 - 08:56 AM

Quote

but it was requested a Server and Client is created each time.

Sounds like this is a contract for pay gig. So here's some advice:

  • Don't take contracts that you don't know how to complete. How can you possibly even give a quote for something you don't understand? How do you know if it will take you 2 hour or 200? Its both insulting and infuriating for the trained experts here to place bids on these same contracts based on actually skill, only to be undercut by a rookie with no clue. Then to add insult to injury that same rookie then asks the guy he beat out how to do the job.
  • Assume the clients are idiots. Get EVERYTHING spelled out in writing. Make no assumptions. So many clients think they are developers and try to throw in tech-speak to sound knowledgeable. Your client may think a client and server are needed because they want two-way communication: Thus each chat client app must be both a client and server, right?


Quote

Would it be better to create the chat window in a different class and use it to add Server's information to pass it into it


Let me rephrase the question the way I hear it:

Quote

I didn't read and DO the tutorials you pointed me to. Just tell me the important parts, and architect my application design for me.


I'm more interested in you learning your tradecraft than I am in you completing this contract. Trial and error. Building the same application 6 different ways. Learning through painting yourself into a corner so you can see the shortcomings of a path. These are all the tools of the upcoming developer. One learns so much more by actually trying new things and experimenting with different approaches.

So to answer your question: Try it. Build it. Learn from doing it. We are an educational site, not a free 'do my engineering design' site. You will learn a lot my by actually building out a version of your application using the technique you asked about.
Was This Post Helpful? 0
  • +
  • -

#5 codecsmash49  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 61
  • Joined: 09-December 08

Re: Client/Server .net remoting and multithreading

Posted 05 November 2012 - 09:02 AM

This is a class assignment to be clear for my college course. If it was a contract I would be using Java which I am a little more knowledgeable with. My Prof decided that C# is better suited for this course and I trying to learn C# for this course.

View PosttlhIn`toq, on 05 November 2012 - 08:56 AM, said:

Quote

but it was requested a Server and Client is created each time.

Sounds like this is a contract for pay gig. So here's some advice:

  • Don't take contracts that you don't know how to complete. How can you possibly even give a quote for something you don't understand? How do you know if it will take you 2 hour or 200? Its both insulting and infuriating for the trained experts here to place bids on these same contracts based on actually skill, only to be undercut by a rookie with no clue. Then to add insult to injury that same rookie then asks the guy he beat out how to do the job.
  • Assume the clients are idiots. Get EVERYTHING spelled out in writing. Make no assumptions. So many clients think they are developers and try to throw in tech-speak to sound knowledgeable. Your client may think a client and server are needed because they want two-way communication: Thus each chat client app must be both a client and server, right?


Quote

Would it be better to create the chat window in a different class and use it to add Server's information to pass it into it


Let me rephrase the question the way I hear it:

Quote

I didn't read and DO the tutorials you pointed me to. Just tell me the important parts, and architect my application design for me.


I'm more interested in you learning your tradecraft than I am in you completing this contract. Trial and error. Building the same application 6 different ways. Learning through painting yourself into a corner so you can see the shortcomings of a path. These are all the tools of the upcoming developer. One learns so much more by actually trying new things and experimenting with different approaches.

So to answer your question: Try it. Build it. Learn from doing it. We are an educational site, not a free 'do my engineering design' site. You will learn a lot my by actually building out a version of your application using the technique you asked about.


I am currently trying to find the tutorials you recommend, but there really is not numerical order for the Tutorials Forum
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5436
  • View blog
  • Posts: 11,649
  • Joined: 02-June 10

Re: Client/Server .net remoting and multithreading

Posted 05 November 2012 - 01:42 PM

Ok - your client is the teacher. Verify his/her definitions of "server & client".
Was This Post Helpful? 0
  • +
  • -

#7 codecsmash49  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 61
  • Joined: 09-December 08

Re: Client/Server .net remoting and multithreading

Posted 14 November 2012 - 10:41 AM

View PosttlhIn`toq, on 05 November 2012 - 01:42 PM, said:

Ok - your client is the teacher. Verify his/her definitions of "server & client".



I finally got to get the specifics of what he wants. He said "A application chat program that handles two threads on each peer to do client and server work for sending and receiving messages.

From his drawing It looks as if I am doing it wrong then. If the client and server are supported to be in the same program then I would have to migrate all of my code into 1 namespace.

I would start the Form1 and initialize 2 threads(1 client 1 server). Sorry If I am asking too much, this program just doesn't make any sense/point in terms of logical application.
Was This Post Helpful? 0
  • +
  • -

#8 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,957
  • Joined: 21-March 08

Re: Client/Server .net remoting and multithreading

Posted 14 November 2012 - 01:26 PM

Quote

I didn't read and DO the tutorials you pointed me to. Just tell me the important parts, and architect my application design for me.


I'm sorry, but we are not here to do your class work for you. We are glad to help and to point you in the right direction, but we will not architect and do your application for you. You learn nothing from us doing the work for you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1