用Socket异步调用实现的一个TCP的网络信息对话

类别:.NET开发 点击:0 评论:0 推荐:

    偶然一天没事干、空虚、无聊、发呆......,总的要给自己找点事情做啊,想来想去,决定用C#做一个pop3、smtp的邮件发送和接收组件,但是又不熟悉pop3、smtp协议,网上狂找一通,有了一点点眉目,但是又没办法试一下这些命令,总不能瞎来吧,怎搞?
    咦,干嘛不作一个网络信息发送和察看接收到的信息的小工具呢?这样不但可以试试pop3、smtp协议的东西,还可以试试ftp、http......说干就干,反正也没事干
    正好那天看了一个什么异步的东西,在msdn上随便看了看,知道了一个大概,那就开搞吧(偶长期半懂不懂的就开搞了,等实在搞不动的时候再查资料)
    结果就搞出来下面一个被偶称为“TCP Net  Dialog”的小工具。

http示例

FTP示例

POP3示例

SMTP示例

源代码如下
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.Text;

namespace NetConnect
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private System.Windows.Forms.TextBox IPTextBox;
  private System.Windows.Forms.TextBox PortTextBox;
  private System.Windows.Forms.Button ConnectButton;
  private System.Windows.Forms.TextBox InputBox;
  private System.Windows.Forms.Label label1;
  private System.Windows.Forms.Label label2;
  private System.Windows.Forms.Label label3;
  private System.Windows.Forms.Button SendButton;
  private System.Windows.Forms.RichTextBox ResultTextBox;
  private System.Windows.Forms.Button button1;
  private System.Windows.Forms.Button ExitButton;
  private System.Windows.Forms.StatusBar statusBar1;
  private System.Windows.Forms.Button DisconnectButton;

  Socket MySocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  string Line="\r\n";//换行符,同时也是网络数据的结束标志
  static int RecvLength=1024*10;//每次接受的字节数
  byte[] RecvBF=new byte[RecvLength];
  string NullString=System.Text.UTF8Encoding.UTF8.GetString(new byte[RecvLength]);


  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows Form Designer generated code
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.IPTextBox = new System.Windows.Forms.TextBox();
   this.PortTextBox = new System.Windows.Forms.TextBox();
   this.ConnectButton = new System.Windows.Forms.Button();
   this.InputBox = new System.Windows.Forms.TextBox();
   this.SendButton = new System.Windows.Forms.Button();
   this.label1 = new System.Windows.Forms.Label();
   this.label2 = new System.Windows.Forms.Label();
   this.label3 = new System.Windows.Forms.Label();
   this.DisconnectButton = new System.Windows.Forms.Button();
   this.ResultTextBox = new System.Windows.Forms.RichTextBox();
   this.button1 = new System.Windows.Forms.Button();
   this.ExitButton = new System.Windows.Forms.Button();
   this.statusBar1 = new System.Windows.Forms.StatusBar();
   this.SuspendLayout();
   //
   // IPTextBox
   //
   this.IPTextBox.Location = new System.Drawing.Point(40, 8);
   this.IPTextBox.Name = "IPTextBox";
   this.IPTextBox.TabIndex = 0;
   this.IPTextBox.Text = "192.168.72.193";
   //
   // PortTextBox
   //
   this.PortTextBox.Location = new System.Drawing.Point(176, 8);
   this.PortTextBox.Name = "PortTextBox";
   this.PortTextBox.Size = new System.Drawing.Size(32, 21);
   this.PortTextBox.TabIndex = 1;
   this.PortTextBox.Text = "80";
   //
   // ConnectButton
   //
   this.ConnectButton.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
   this.ConnectButton.Location = new System.Drawing.Point(224, 8);
   this.ConnectButton.Name = "ConnectButton";
   this.ConnectButton.TabIndex = 2;
   this.ConnectButton.Text = "Connect";
   this.ConnectButton.Click += new System.EventHandler(this.ConnectButton_Click);
   //
   // InputBox
   //
   this.InputBox.Anchor = ((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
    | System.Windows.Forms.AnchorStyles.Right);
   this.InputBox.Location = new System.Drawing.Point(64, 40);
   this.InputBox.Multiline = true;
   this.InputBox.Name = "InputBox";
   this.InputBox.Size = new System.Drawing.Size(232, 104);
   this.InputBox.TabIndex = 3;
   this.InputBox.Text = "";
   this.InputBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.InputBox_KeyUp);
   //
   // SendButton
   //
   this.SendButton.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
   this.SendButton.Location = new System.Drawing.Point(312, 48);
   this.SendButton.Name = "SendButton";
   this.SendButton.TabIndex = 4;
   this.SendButton.Text = "Send";
   this.SendButton.Click += new System.EventHandler(this.SendButton_Click);
   //
   // label1
   //
   this.label1.Location = new System.Drawing.Point(8, 8);
   this.label1.Name = "label1";
   this.label1.Size = new System.Drawing.Size(32, 23);
   this.label1.TabIndex = 7;
   this.label1.Text = "IP";
   //
   // label2
   //
   this.label2.Location = new System.Drawing.Point(144, 8);
   this.label2.Name = "label2";
   this.label2.Size = new System.Drawing.Size(32, 23);
   this.label2.TabIndex = 8;
   this.label2.Text = "Port";
   //
   // label3
   //
   this.label3.Location = new System.Drawing.Point(8, 40);
   this.label3.Name = "label3";
   this.label3.Size = new System.Drawing.Size(48, 23);
   this.label3.TabIndex = 9;
   this.label3.Text = "Message";
   //
   // DisconnectButton
   //
   this.DisconnectButton.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
   this.DisconnectButton.Location = new System.Drawing.Point(312, 8);
   this.DisconnectButton.Name = "DisconnectButton";
   this.DisconnectButton.TabIndex = 10;
   this.DisconnectButton.Text = "Disconnect";
   this.DisconnectButton.Click += new System.EventHandler(this.DisconnectButton_Click);
   //
   // ResultTextBox
   //
   this.ResultTextBox.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
    | System.Windows.Forms.AnchorStyles.Left)
    | System.Windows.Forms.AnchorStyles.Right);
   this.ResultTextBox.Location = new System.Drawing.Point(8, 160);
   this.ResultTextBox.Name = "ResultTextBox";
   this.ResultTextBox.ReadOnly = true;
   this.ResultTextBox.Size = new System.Drawing.Size(384, 312);
   this.ResultTextBox.TabIndex = 11;
   this.ResultTextBox.Text = "";
   this.ResultTextBox.WordWrap = false;
   //
   // button1
   //
   this.button1.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
   this.button1.Location = new System.Drawing.Point(312, 80);
   this.button1.Name = "button1";
   this.button1.TabIndex = 12;
   this.button1.Text = "Clear";
   this.button1.Click += new System.EventHandler(this.button1_Click);
   //
   // ExitButton
   //
   this.ExitButton.Anchor = (System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right);
   this.ExitButton.Location = new System.Drawing.Point(312, 112);
   this.ExitButton.Name = "ExitButton";
   this.ExitButton.TabIndex = 13;
   this.ExitButton.Text = "Exit";
   this.ExitButton.Click += new System.EventHandler(this.ExitButton_Click);
   //
   // statusBar1
   //
   this.statusBar1.Location = new System.Drawing.Point(0, 477);
   this.statusBar1.Name = "statusBar1";
   this.statusBar1.Size = new System.Drawing.Size(400, 16);
   this.statusBar1.TabIndex = 14;
   this.statusBar1.Text = "Programed by xuexplorer                mail:[email protected]";
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(400, 493);
   this.Controls.AddRange(new System.Windows.Forms.Control[] {
                    this.statusBar1,
                    this.ExitButton,
                    this.button1,
                    this.ResultTextBox,
                    this.DisconnectButton,
                    this.label3,
                    this.label2,
                    this.label1,
                    this.SendButton,
                    this.InputBox,
                    this.ConnectButton,
                    this.PortTextBox,
                    this.IPTextBox});
   this.Name = "Form1";
   this.Text = "TCP Net  Dialog";
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  /// <summary>
  /// 连接
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void ConnectButton_Click(object sender, System.EventArgs e)
  {
   try
   {
    if(MySocket.Connected)
     return;

    IPAddress ip=IPAddress.Parse(IPTextBox.Text);
    int port=int.Parse(PortTextBox.Text);
    IPEndPoint ipEP=new IPEndPoint(ip,port);
    MySocket.Connect((EndPoint)ipEP);
    if(MySocket.Connected)
    {
     this.ResultTextBox.Text+="Connect "+IPTextBox.Text+":"+PortTextBox.Text+" Successfully"+Line;

     MySocket.BeginReceive(RecvBF,0,RecvBF.Length,0,new System.AsyncCallback(ReceiveMessage),MySocket);
    }
   }
   catch(Exception ex)
   {
    this.ResultTextBox.Text+="Connect "+IPTextBox.Text+":"+PortTextBox.Text+" Unsuccessfully"+Line;
   }
  }

  /// <summary>
  /// 断开连接
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void DisconnectButton_Click(object sender, System.EventArgs e)
  {
   DisConnect();
  }

  /// <summary>
  /// 断开连接
  /// </summary>
  private void DisConnect()
  {
   if(MySocket.Connected)
   {
    MySocket.Shutdown(SocketShutdown.Both);
    MySocket.Close();
    this.ResultTextBox.Text+=Line+"Connection Closed"+Line;
    MySocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
   }
  }

  /// <summary>
  /// 回调函数,接受信息
  /// </summary>
  /// <param name="result"></param>
  private void ReceiveMessage(System.IAsyncResult result)
  {
   string str=System.Text.UTF8Encoding.Default.GetString(RecvBF);
   RecvBF=new byte[RecvLength];
   if(str!=NullString)
   {
    this.ResultTextBox.Text+="Recv:"+str+Line;
   }
   else
   {
    DisConnect();
   }
   if(MySocket.Connected)
   {
    MySocket.EndReceive(result);
    MySocket.BeginReceive(RecvBF,0,RecvBF.Length,0,new System.AsyncCallback(ReceiveMessage),MySocket);
   }
  }

  /// <summary>
  /// 发送信息
  /// </summary>
  private void SendMessage()
  {
   if(!MySocket.Connected)
   {
    this.ResultTextBox.Text+="No Connection"+Line;
    return;
   }
   string msg=this.InputBox.Text;
   
   try
   {
    byte[] SendBF=new byte[1024];
    SendBF=System.Text.UTF8Encoding.UTF8.GetBytes(msg);
    MySocket.Send(SendBF);
    this.ResultTextBox.Text+="Send:\""+this.InputBox.Text+"\" Successfully"+Line;
    
   }
   catch
   {
    this.ResultTextBox.Text+="Send:\""+this.InputBox.Text+"\" Unsuccessfully"+Line;
   }
   finally
   {
    this.InputBox.Clear();
   }
  }

  /// <summary>
  /// 发送信息
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void SendButton_Click(object sender, System.EventArgs e)
  {
   SendMessage();
  }

  /// <summary>
  /// 清除结果
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void button1_Click(object sender, System.EventArgs e)
  {
   this.ResultTextBox.Clear();
  }

  /// <summary>
  /// 退出
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void ExitButton_Click(object sender, System.EventArgs e)
  {
   DisConnect();
   Dispose(true);
  }

  /// <summary>
  /// 信息输入框中按Ctrl+Enter组合键
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void InputBox_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
  {
   if ((e.KeyData & Keys.Control) == Keys.Control && (e.KeyData & Keys.Enter) == Keys.Enter)
   {
    int i=InputBox.Text.LastIndexOf(Line);
    this.InputBox.Text=this.InputBox.Text.Substring(0,InputBox.Text.LastIndexOf("\r\n"));
   
    SendMessage();
   }
  }
 }
}

    也没啥详细的说明,因为我也是半懂不懂,怕说错了误导了初学者,异步调用相关内容请到msdn中查询“异步调用”。
    作这个东西只是为了好玩,消磨时间而已。

本文地址:http://com.8s8s.com/it/it41672.htm