C#client-server vs multiclient-server c#

时间:2017-05-17 22:58:14

标签: c# networking server client

有人可以向我解释c#中单个客户端服务器和多客户端服务器之间的区别吗?

如果我想同时与许多客户建立一个聊天室,我不确定我是否理解正确,但是我们只为每个客户分配新的IP并且服务器会读取它们吗?

这是客户端代码

        public Form1()
    {
        //
        // Required for Windows Form Designer support
        //
        InitializeComponent();
        read=new Thread(new ThreadStart(RunClient));
        read.Start();
    }

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    protected override void Dispose( bool disposing )
    {
        if( disposing )
        {
            if (components != null) 
            {
                components.Dispose();
            }
        }
        base.Dispose( disposing );
    }

    #region Windows Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
        //this.axSkin1 = new AxACTIVESKINLib.AxSkin();
        this.tmsg = new System.Windows.Forms.TextBox();
        this.bsend = new System.Windows.Forms.Button();
        this.groupBox1 = new System.Windows.Forms.GroupBox();
        this.tchat = new System.Windows.Forms.RichTextBox();
        this.Message = new System.Windows.Forms.GroupBox();
        this.Box1 = new System.Windows.Forms.PictureBox();
        //((System.ComponentModel.ISupportInitialize)(this.axSkin1)).BeginInit();
        this.groupBox1.SuspendLayout();
        this.SuspendLayout();
        // 
        // axSkin1
        // 
        //this.axSkin1.Enabled = true;
        //this.axSkin1.Location = new System.Drawing.Point(368, 272);
        //this.axSkin1.Name = "axSkin1";
        //this.axSkin1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axSkin1.OcxState")));
        //this.axSkin1.Size = new System.Drawing.Size(32, 32);
        //this.axSkin1.TabIndex = 0;
        //// 
        // tmsg
        // 
        this.tmsg.ForeColor = System.Drawing.Color.Coral;
        this.tmsg.Location = new System.Drawing.Point(32, 268);
        this.tmsg.Name = "tmsg";
        this.tmsg.Size = new System.Drawing.Size(336, 20);
        this.tmsg.TabIndex = 0;
        this.tmsg.Text = "";
        this.tmsg.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.tmsg_KeyPress);
        // 
        // bsend
        // 
        this.bsend.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
        this.bsend.ForeColor = System.Drawing.Color.OrangeRed;
        this.bsend.Location = new System.Drawing.Point(168, 311);
        this.bsend.Name = "bsend";
        this.bsend.Size = new System.Drawing.Size(64, 24);
        this.bsend.TabIndex = 3;
        this.bsend.Text = "&send";
        this.bsend.Click += new System.EventHandler(this.bsend_Click);
        // 
        // groupBox1
        // 
        this.groupBox1.Controls.Add(this.tchat);
        this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(178)));
        this.groupBox1.ForeColor = System.Drawing.Color.Black;
        this.groupBox1.Location = new System.Drawing.Point(24, 56);
        this.groupBox1.Name = "groupBox1";
        this.groupBox1.Size = new System.Drawing.Size(352, 176);
        this.groupBox1.TabIndex = 4;
        this.groupBox1.TabStop = false;
        this.groupBox1.Text = "Message Exchange";
        // 
        // tchat
        // 
        this.tchat.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(178)));
        this.tchat.Location = new System.Drawing.Point(16, 24);
        this.tchat.Name = "tchat";
        this.tchat.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.ForcedVertical;
        this.tchat.Size = new System.Drawing.Size(320, 136);
        this.tchat.TabIndex = 0;
        this.tchat.Text = "";
        // 
        // Message
        // 
        this.Message.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(178)));
        this.Message.ForeColor = System.Drawing.Color.Black;
        this.Message.Location = new System.Drawing.Point(24, 244);
        this.Message.Name = "Message";
        this.Message.Size = new System.Drawing.Size(352, 56);
        this.Message.TabIndex = 5;
        this.Message.TabStop = false;
        this.Message.Text = "Message";
        // 
        // Box1
        // 
        this.Box1.Location = new System.Drawing.Point(299, 3);
        this.Box1.Name = "Box1";
        this.Box1.Size = new System.Drawing.Size(72, 51);
        this.Box1.TabIndex = 6;
        this.Box1.TabStop = false;
        // 
        // Form1
        // 
        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.BackColor = System.Drawing.SystemColors.ControlLightLight;
        this.ClientSize = new System.Drawing.Size(400, 342);
        this.Controls.Add(this.Box1);
        this.Controls.Add(this.bsend);
        this.Controls.Add(this.tmsg);
        //this.Controls.Add(this.axSkin1);
        this.Controls.Add(this.groupBox1);
        this.Controls.Add(this.Message);
        this.Location = new System.Drawing.Point(432, 408);
        this.MaximumSize = new System.Drawing.Size(408, 376);
        this.MinimumSize = new System.Drawing.Size(408, 376);
        this.Name = "Form1";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Client";
        this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
        this.Load += new System.EventHandler(this.Form1_Load);
        //((System.ComponentModel.ISupportInitialize)(this.axSkin1)).EndInit();
        this.groupBox1.ResumeLayout(false);
        this.ResumeLayout(false);

    }
    #endregion

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main() 
    {
        Application.Run(new Form1());
    }

    private void Form1_Load(object sender, System.EventArgs e)
    {
        //axSkin1.ApplySkin((int)Handle);
    }

    //---------------------------------------------------------
    public void RunClient()
    {
        try
        {
            this.Icon=new Icon("1.ico");
            this.Box1.Image=Image.FromFile("1.gif");
        }
        catch(Exception e)
        {
            MessageBox.Show(e.Message);
        }
        try
        {
            tchat.Text="trying to connect to the server";
            // Step 1: create TcpClient and connect to server
            client=new TcpClient();
            client.Connect("LocalHost",20000);
            // Step 2: get NetworkStream associated with TcpClient
            stream=client.GetStream();
            // create objects for writing and reading across stream
            reader=new BinaryReader(stream);
            writer=new BinaryWriter(stream);
            //send welcome to server
            writer.Write("Welcome server");
            tchat.Text+="\r\n Client :Welcome server";
            string reply;
            while(true)
            {
                //step 3: read message from server
                try
                {
                    reply=reader.ReadString();
                    int len=tchat.Text.Length;
                    tchat.AppendText("\r\nServer :"+reply);
                    tchat.Select(len,10+reply.Length);
                    tchat.SelectionColor=Color.Red;
                    tchat.ScrollToCaret();
                }
                //handle execption if the server terminate
                catch(Exception)
                {
                    //step 5:close connection
                    MessageBox.Show("Can not find server..!");
                    reader.Close();
                    writer.Close();
                    stream.Close();
                    client.Close();
                }
            }
        }
        catch(Exception)
        {
            MessageBox.Show(this,"Error while connecting to server",
                this.Text,MessageBoxButtons.OK,
                MessageBoxIcon.Error,
                MessageBoxDefaultButton.Button1);
        }

    }
    private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        System.Environment.Exit(System.Environment.ExitCode);
    }

    private void tmsg_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        if(e.KeyChar=='\r'&&client!=null)
        {

            writer.Write(tmsg.Text);
            int len=tchat.TextLength;
            tchat.AppendText("\r\nClient  :"+tmsg.Text);
            tchat.Select(len,10+tmsg.TextLength);
            tchat.SelectionColor=Color.Blue;
            tmsg.Clear();
        }
    }

    private void bsend_Click(object sender, System.EventArgs e)
    {
        if(client!=null)
        {
            writer.Write(tmsg.Text);
            int len=tchat.TextLength;
            tchat.AppendText("\r\nClient  :"+tmsg.Text);
            tchat.Select(len,10+tmsg.TextLength);
            tchat.SelectionColor=Color.Blue;
            tmsg.Clear();
        }

    }
}

如果需要,我也可以发布服务器代码,讲师说他至少会欣赏这个尝试。

好的,所以我无法对其进行格式化,所以这里是服务器代码https://pastebin.com/bzhr20Qk

1 个答案:

答案 0 :(得分:0)

从根本上说没有区别;服务器应用程序的性质是:

  • 拥有一个侦听一次或多次连接尝试的侦听器
  • 检测到连接尝试时,初始化某种代码以处理该连接,然后推测返回侦听连接尝试

有趣的是:你如何处理这种连接?如果您只期望一个客户端,您可以在一个线程中执行所有操作:

  • 等待连接
  • 等待完整的传入消息
    • 处理收到的消息
    • (重复)

如果您希望连接数,则可以提供每个连接的线程数:

  • 等待连接
    • 为该连接启动一个帖子
    • (重复)

with(每个连接)

  • 等待完整的传入消息
    • 处理收到的消息
    • (重复)

但是,对于任何非平凡的事情,每个连接的线程根本不起作用;你需要开始考虑异步代码和IO回调,共享缓冲区以及各种疯狂。很难做对。来源:目前正在为452,256个TCP / IP连接提供服务。

回答具体问题:

  

但是我们只为每个客户端分配新的IP并且服务器会读取它们吗?

不,客户端IP是客户端IP是客户端IP。客户端连接到侦听器端口,然后在服务器上,侦听器将移交到临时端口上的已建立的 TCP连接。你通常不需要担心这一点,它是自动处理的。但端口号实际连接之间有所不同。