网络编程 | 站长之家 | 网页制作 | 图形图象 | 操作系统 | 冲浪宝典 | 软件教学 | 网络办公 | 邮件系统 | 网络安全 | 认证考试 | 系统进程
Firefox | IE | Maxthon | 迅雷 | 电驴 | BitComet | FlashGet | QQ | QQ空间 | Vista | 输入法 | Ghost | Word | Excel | wps | Powerpoint
asp | .net | php | jsp | Sql | c# | Ajax | xml | Dreamweaver | FrontPages | Javascript | css | photoshop | fireworks | Flash | Cad | Discuz!
当前位置 > 网站建设学院 > 网络编程 > C#应用
Tag:注入,存储过程,分页,安全,优化,xmlhttp,fso,jmail,application,session,防盗链,stream,无组件,组件,md5,乱码,缓存,加密,验证码,算法,cookies,ubb,正则表达式,水印,索引,日志,压缩,base64,url重写,上传,控件,Web.config,JDBC,函数,内存,PDF,迁移,结构,破解,编译,配置,进程,分词,IIS,Apache,Tomcat,phpmyadmin,Gzip,触发器,socket
网络编程:ASP教程,ASP.NET教程,PHP教程,JSP教程,C#教程,数据库,XML教程,Ajax,Java,Perl,Shell,VB教程,Delphi,C/C++教程,软件工程,J2EE/J2ME,移动开发
本月文章推荐
.使用C#创建SQL Server的存储过程.
.RadioBox、CheckBox和Validating.
.C#实现Word中表格信息读取.
.关于C#和C++的重载(Overload)、.
.StringWriter实现的一个功能.
.C# Enum设计和使用的相关技巧 .
.像Asp一样轻松分页显示数据(C#) .
..net中前台javascript与c#后台代.
.c# 正确读取存储中文,以及如何获.
.C#中时间格式的转换.
.在指定应用程序域中执行代码.
.用Visual C#来删除注册表中的注.
.借用VB的My,C#照样条条大路通罗.
.利用c#制作简单的留言板(4) .
.从DataGridView控件托放数据到Tr.
.用C#实现智能设备上的NotifyIcon.
.在C#中使用可空类型.
.C# 中启动进程的三种方法.
.C#实现WEB服务器.
.在C#应用程序与DLL交互中使用消息.

C#实现Socket传输简单数据

发表日期:2007-3-21


运行程序后, 先要点击开始接收按钮后才能点击发送数据

Form1.cs代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Net;

namespace WinSocket
...{
    public partial class Form1 : Form
    ...{
        BackgroundWorker bgWorker = null;
        public Form1()
        ...{
            InitializeComponent();
            bgWorker = new BackgroundWorker();
            bgWorker.WorkerSupportsCancellation = true;
            this.AddEvent();
        }

        /**//// <summary>
        /// 注册事件
        /// </summary>
        private void AddEvent()
        ...{
            this.bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            this.btnSend.Click += new EventHandler(btnSend_Click);
            this.btnStartReceive.Click += new EventHandler(btnStartReceive_Click);
            this.btnStopRecevie.Click += new EventHandler(btnStopRecevie_Click);
        }

        void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        ...{
            Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint endpoint = new IPEndPoint(0, 8000);

            receiveSocket.Bind(endpoint);
            receiveSocket.Listen(10);

          
            try
            ...{
                while (true)
                ...{
                    Socket tmpSocket = receiveSocket.Accept();
                    byte[] buffer = new byte[tmpSocket.ReceiveBufferSize];
                    if (tmpSocket.Receive(buffer) > 0)
                    ...{
                        textBox2.Text += Encoding.UTF8.GetString(buffer) + Environment.NewLine;                     
                    }
                    else
                    ...{
                        System.Threading.Thread.Sleep(1000);
                    }

                }
            }
            catch(Exception err)
            ...{
                MessageBox.Show(err.Message);
            }
        }

        void btnStopRecevie_Click(object sender, EventArgs e)
        ...{
            if (this.bgWorker.IsBusy)
            ...{
                this.bgWorker.CancelAsync();
                this.btnStartReceive.Enabled = true;
                this.btnStopRecevie.Enabled = false;
            }          
        }

        void btnStartReceive_Click(object sender, EventArgs e)
        ...{
            this.btnStartReceive.Enabled = false;
            this.bgWorker.RunWorkerAsync();
            this.btnStopRecevie.Enabled = true;
        }

        void btnSend_Click(object sender, EventArgs e)
        ...{
            Socket sendSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sendSocket.Connect("187.186.0.63", 8000);

            byte[] buffer = Encoding.UTF8.GetBytes(textBox1.Text);           
           
            sendSocket.Send(buffer);
          
            sendSocket.Shutdown(SocketShutdown.Both);
            sendSocket.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        ...{
            this.btnStartReceive.Enabled = true;
            this.btnStopRecevie.Enabled = false;           
        }
    }
}
Form.Designer.cs代码如下

 

namespace WinSocket
...{
    partial class Form1
    ...{
        /**//// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /**//// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        ...{
            if (disposing && (components != null))
            ...{
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        Windows 窗体设计器生成的代码#region Windows 窗体设计器生成的代码

        /**//// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        ...{
            this.btnSend = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.btnStartReceive = new System.Windows.Forms.Button();
            this.btnStopRecevie = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // btnSend
            //
            this.btnSend.Location = new System.Drawing.Point(164, 35);
            this.btnSend.Name = "btnSend";
            this.btnSend.Size = new System.Drawing.Size(75, 23);
            this.btnSend.TabIndex = 0;
            this.btnSend.Text = "发送";
            this.btnSend.UseVisualStyleBackColor = true;
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(24, 37);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(100, 21);
            this.textBox1.TabIndex = 1;
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(24, 123);
            this.textBox2.Multiline = true;
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(234, 131);
            this.textBox2.TabIndex = 2;
          
            //
            // btnStartReceive
            //
            this.btnStartReceive.Location = new System.Drawing.Point(24, 84);
            this.btnStartReceive.Name = "btnStartReceive";
            this.btnStartReceive.Size = new System.Drawing.Size(75, 23);
            this.btnStartReceive.TabIndex = 3;
            this.btnStartReceive.Text = "开始接收";
            this.btnStartReceive.UseVisualStyleBackColor = true;
            //
            // btnStopRecevie
            //
            this.btnStopRecevie.Location = new System.Drawing.Point(164, 84);
            this.btnStopRecevie.Name = "btnStopRecevie";
            this.btnStopRecevie.Size = new System.Drawing.Size(75, 23);
            this.btnStopRecevie.TabIndex = 4;
            this.btnStopRecevie.Text = "停止接收";
            this.btnStopRecevie.UseVisualStyleBackColor = true;
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.btnStopRecevie);
            this.Controls.Add(this.btnStartReceive);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.btnSend);
            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 btnSend;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.Button btnStartReceive;
        private System.Windows.Forms.Button btnStopRecevie;
    }
}

上一篇:在C#中运用SQLDMO备份和恢复Microsoft SQL Server数据库 人气:4275
下一篇:C#中接口的深入浅出 人气:5091
浏览全部C#的内容 Dreamweaver插件下载 网页广告代码 祝你圣诞节快乐 2009年新年快乐