c#套接字编程(客户端)


想要更详细的,请到我的资源上去下载!
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;//新加的
using System.Net.Sockets;//新加的
using System.Threading;

namespace Sock_Conn
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Button button2;
        private IPAddress myIP=IPAddress.Parse("127.0.0.1");//新加的
        private IPEndPoint  MyServer;//新加的
        private Socket sock;
        private bool bb=true;
        private static ManualResetEvent connectDone =
            new ManualResetEvent(false);
        private static ManualResetEvent sendDone =
            new ManualResetEvent(false);
        private static ManualResetEvent receiveDone =
            new ManualResetEvent(false);

        private System.Windows.Forms.StatusBar statusBar1;
        private System.Windows.Forms.StatusBarPanel statusBarPanel1;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.Label label4;
        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.RichTextBox richTextBox2;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.TextBox textBox3;//新加的
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <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()
        {
            this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
            this.label4 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.statusBar1 = new System.Windows.Forms.StatusBar();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.button3 = new System.Windows.Forms.Button();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.richTextBox2 = new System.Windows.Forms.RichTextBox();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.textBox3 = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            //
            // statusBarPanel1
            //
            this.statusBarPanel1.Name = "statusBarPanel1";
            this.statusBarPanel1.Width = 300;
            //
            // label4
            //
            this.label4.Location = new System.Drawing.Point(24, 160);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(88, 23);
            this.label4.TabIndex = 11;
            this.label4.Text = "发送信息:";
            //
            // label1
            //
            this.label1.Location = new System.Drawing.Point(24, 32);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(72, 23);
            this.label1.TabIndex = 0;
            this.label1.Text = "服务器IP:";
            //
            // label2
            //
            this.label2.Location = new System.Drawing.Point(24, 64);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(72, 23);
            this.label2.TabIndex = 2;
            this.label2.Text = "请求端口:";
            //
            // label3
            //
            this.label3.Location = new System.Drawing.Point(24, 96);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(80, 23);
            this.label3.TabIndex = 10;
            this.label3.Text = "接受信息:";
            //
            // statusBar1
            //
            this.statusBar1.Location = new System.Drawing.Point(0, 265);
            this.statusBar1.Name = "statusBar1";
            this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
            this.statusBarPanel1});
            this.statusBar1.ShowPanels = true;
            this.statusBar1.Size = new System.Drawing.Size(376, 20);
            this.statusBar1.TabIndex = 6;
            this.statusBar1.PanelClick += new System.Windows.Forms.StatusBarPanelClickEventHandler(this.statusBar1_PanelClick);
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(120, 64);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(152, 21);
            this.textBox2.TabIndex = 4;
            this.textBox2.Text = "6688";
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(120, 32);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(152, 21);
            this.textBox1.TabIndex = 1;
            this.textBox1.Text = "192.168.0.22";
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(24, 224);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 3;
            this.button1.Text = "请求连接";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            //
            // button2
            //
            this.button2.Location = new System.Drawing.Point(272, 224);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(75, 24);
            this.button2.TabIndex = 5;
            this.button2.Text = "关闭连接";
            this.button2.Click += new System.EventHandler(this.button2_Click);
            //
            // button3
            //
            this.button3.Location = new System.Drawing.Point(152, 224);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(75, 23);
            this.button3.TabIndex = 8;
            this.button3.Text = "发送消息";
            this.button3.Click += new System.EventHandler(this.button3_Click);
            //
            // richTextBox1
            //
            this.richTextBox1.Location = new System.Drawing.Point(120, 96);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(256, 48);
            this.richTextBox1.TabIndex = 12;
            this.richTextBox1.Text = "";
            this.richTextBox1.TextChanged += new System.EventHandler(this.richTextBox1_TextChanged);
            //
            // richTextBox2
            //
            this.richTextBox2.Location = new System.Drawing.Point(120, 160);
            this.richTextBox2.Name = "richTextBox2";
            this.richTextBox2.Size = new System.Drawing.Size(256, 48);
            this.richTextBox2.TabIndex = 13;
            this.richTextBox2.Text = "";
            //
            // groupBox1
            //
            this.groupBox1.Controls.Add(this.textBox3);
            this.groupBox1.Location = new System.Drawing.Point(272, 24);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(104, 64);
            this.groupBox1.TabIndex = 14;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "注册(昵称)";
            //
            // textBox3
            //
            this.textBox3.Location = new System.Drawing.Point(8, 24);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(88, 21);
            this.textBox3.TabIndex = 0;
            //
            // Form1
            //
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
            this.ClientSize = new System.Drawing.Size(376, 285);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.richTextBox2);
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.statusBar1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.label1);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "Form1";
            this.Text = "聊天程序-客户端";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

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

        private void button1_Click(object sender, System.EventArgs e)
        {
            //....请求连接到服务器
            try
            {
                myIP =IPAddress.Parse(textBox1.Text);//ip地址
           
            }
            catch{MessageBox.Show("您输入的IP地址格式不正确,请重新输入!");}
            try
            {
                MyServer=new IPEndPoint(myIP,Int32.Parse(textBox2.Text));//ip地址和端口号组成的
                sock =new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//定义套接字类型
                sock.Connect(MyServer);//通过套接字链接主机(ipendport)
                    statusBarPanel1.Text="与主机"+textBox1.Text+"端口"+textBox2.Text+"连接成功!";
                    bb = true;
                Thread thread=new Thread(new ThreadStart(targett));
                thread.Start();
               
            }
            catch(Exception ee){MessageBox.Show(ee.Message);}
          
        }

        private void button2_Click(object sender, System.EventArgs e)
        {
            try
            {
                sock.Close();
                statusBarPanel1.Text="与主机"+textBox1.Text+"端口"+textBox2.Text+"断开连接!";
            }
            catch{MessageBox.Show("连接尚未建立,断开无效!");}
        }

        private void button3_Click(object sender, System.EventArgs e)
        {
            button1_Click(null,null);
            try
            {
                Byte[]  bytee=new Byte[640];
                string send=textBox3.Text+">>>>"+richTextBox2.Text+"/r/n";//发送的字符串
                bytee = System.Text.Encoding.UTF8.GetBytes(send.ToCharArray());//发送字符串转换为字节数组
                sock.Send(bytee,bytee.Length,0);//通过套接字发送字节数组
               
            }
            catch{MessageBox.Show("连接尚未建立!无法发送!");}
           
        }
        Socket s;
        private void targett()
        {
            try
            {
                while (bb)
                {
                     s = sock;
                    Byte[] bbb = new Byte[640];
                    s.Receive(bbb, bbb.Length, 0);//套接字接收缓冲区里的数据读取到字节数组中
                    string aaaaa = System.Text.Encoding.UTF8.GetString(bbb);//字节数组转换为字符串
                    richTextBox1.AppendText(aaaaa);
                    s.Close();
                }
            }
            catch
            {
                MessageBox.Show("连接尚未建立!无法发送!");
            }
          
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void statusBar1_PanelClick(object sender, StatusBarPanelClickEventArgs e)
        {

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            s.Close();
            bb = false;
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值