C/S 架構的簡單Socket 通訊的例子

來源:互聯網
上載者:User

建立兩個Form程式

引用命名空間:using System.Net; using System.Net.Sockets;

Server 端:

放兩個Button和兩個TextBox   

public partial class Form1 : Form
{

   Socket s = null;

     IPEndPoint iep = null;

   byte[] buf = new byte[1024];

     Socket worker = null;

   public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

   private void button1_Click(object sender,EventArgs e)

  {

    //建立一個通道

    s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

    //建立一個偵聽點

    iep = new IPEndPoint(IPAddress.Any,20000);

    //綁定到通道上

    s.Bind(iep);

    //偵聽

    s.Listen(6);

    //通過非同步來處理

    s.BeginAccept(new AsyncCallback(Accept),s);

    this.button1.Visable = false;

  }

  void Accept(IAsyncResult ia)

  {

    s = ia.AsyncState as Socket;

    worker = s.EndAccept();

    s.BeginAccept(new AsyncCallback(Accept),s);

    try

    {

      worker.BeginReceive(buf,0,buf.Length,Socket.Flogs.None, new AsyncCallback(Receive),worker);

    }

    catch

    { throw ;}

  }

  void Receive(IAsyncResult ia)

  {

    worker = ia.AsyncState as Socket;

    int count = worker.EndReceive(ia);

    worker.BeginReceive(buf,0,buf.Length,Socket.Flogs.None,new AsyncCallback(Receive),worker);

    string context = Encoding.GetEncoding("gb2312").GetString(buf,0,count);

    this.textbox1.text += Environment.NewLine;

    this.textbox1.text += context;

  }

  private void button2_Click(object sender, EventArgs e)

  {

    string context ="XXXXX" + this.textbox2.Text.Trim();

    if(context != "")

    {

      this.textbox1.Text += Environment.NewLine;

      this.textbox1.Text += context;

      this.textbox2.Text = "";

      worker.Send(Encoding.GetEncoding("gb2312").GetBytes(context));

    }

  }
}

 

用戶端:

主要代碼:

public partial class Form1 : Form
{

  Socket s = null;

  IPEndPoint iep = null;

  byte[] buf = new byte[1024];

  public Form1()
     {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
      }

  private void button1_Click(object sender,EventArgs e)

  {

    s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

    iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),20000);

    try

    {

      s.Connect(iep);

      this.label1.Text = "串連成功";

      this.button1.Visable =false;

    }

    catch

    { throw ;}

  }

  private void button2_Click(object sender, EventArgs e)

  {

    string context = iep.ToString() + ":" + this.textbox2.Text.Trim();

    if(context != "")

    {

      this.textbox1.Text += Environment.NewLine;

      this.textbox1.Text += context;

      this.tetxbox2.Text ="";

      s.Send(Encoding.GetEncoding("gb2312").GetBytes(context));

      try

      {

        s.BeginReceive(buf,0,buf.Length,Socket.Flogs.None, new AsyncCallback(Receive),s);

      }

      catch

      { throw ;}

    }

  }

  void Receive(IAsynvResult ia)

  {

    s = ia.AsyncState as Socket;

    int count = s.EndReceive(ia);

    s.BeginReceive(buf,0,buf.Length,Socket.Flogs.None, new AsyncCallback(Receive),s);

    string context =Encoding.GetEncoding("gb2312").GetString(buf,0,count);

    this.textbox1.Text += Environment.NewLine;

    this.textbox1.Text += context;

  }

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.