Socket編程 消息傳送 TCP協議(窗口實現) 客戶端

//code

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.Net;
using System.Net.Sockets;
using System.Threading;
namespace ClientSocket_xzh
{
    public partial class Form1 : Form
    {
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        private int port = 9999;
        Byte[] result = new Byte[2048];
        Thread th = null;
        int i = 0;

        public Form1()
        {
                    InitializeComponent();
                    button1.Enabled = false;
                    button2.Enabled = true;
                    TextBox.CheckForIllegalCrossThreadCalls = false;// invalid thread check
           }

               


                //start service
                private void button2_Click(object sender, EventArgs e)
                {
                    button2.Enabled = false;
                    button1.Enabled = true;
                    try
                    {
                        client.Connect(new IPEndPoint(ip, port));
                        th = new Thread(new ThreadStart(GetMsg));
                        th.IsBackground = true;
                        th.Start();
                        textBox1.AppendText("Link success!!\r\n");
                    }
                    catch (SocketException s)
                    {
                        Console.WriteLine(s.ToString());
                        textBox1.AppendText("Link failed!!");
                    }

                }


                //stop service
                private void button1_Click(object sender, EventArgs e)
                {
                    button1.Enabled = false;
                    button2.Enabled = true;
                    try
                    {
                        client.Close();
                        textBox1.AppendText("Link closed!!");
                    }
                    catch (SocketException s)
                    {
                        Console.WriteLine(s.ToString());
                        textBox1.AppendText("Link close error!!");
                    }
                }


                //send message
                private void button3_Click(object sender, EventArgs e)
                {

                    string msg = textBox2.Text.Trim();
                    try
                    {
                        client.Send(ASCIIEncoding.ASCII.GetBytes("12"));
                        Console.WriteLine("i said:" + msg);
                        textBox1.AppendText("i said:" + msg);
                    }
                    catch (SocketException s)
                    {
                        Console.WriteLine(s.ToString());
                        textBox1.AppendText("server said: error!!");
                    }
                }

    
                //get message
                private void GetMsg()
                {
                    try{
                     while (true)
                    {
                        byte[] arrRecMsg = new byte[1024];
                        int length = client.Receive(arrRecMsg);
                        string strRecMsg = Encoding.UTF8.GetString(arrRecMsg, 0, length);
                        textBox1.AppendText("server said:"+ strRecMsg + "\r\n");
                    }
                    }
                    catch (SocketException s)
                    {
                        client.Close();
                        client.Dispose();
                        Console.WriteLine(s.ToString());
                    }
                }

                private void Form1_Load(object sender, EventArgs e)
                {

                }
                }
            }
// design code

namespace ClientSocket_xzh
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (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()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(163, 23);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "End";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(66, 23);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 23);
            this.button2.TabIndex = 1;
            this.button2.Text = "Start";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // button3
            //
            this.button3.Location = new System.Drawing.Point(198, 185);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(75, 23);
            this.button3.TabIndex = 0;
            this.button3.Text = "Send";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.button3_Click);
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(12, 55);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(53, 12);
            this.label1.TabIndex = 3;
            this.label1.Text = "Message:";
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(66, 52);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.textBox1.Size = new System.Drawing.Size(186, 107);
            this.textBox1.TabIndex = 4;
            this.textBox1.Text = "Pls input message ";
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(66, 185);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(126, 21);
            this.textBox2.TabIndex = 5;
            this.textBox2.Text = "werwer";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章