程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C# 2.0套接字編程實例初探(4)

C# 2.0套接字編程實例初探(4)

編輯:關於C語言

客戶端

// Form1.Designer.cs
namespace ClIEntTest
{
  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.listBox1 = new System.Windows.Forms.ListBox();
      this.button1 = new System.Windows.Forms.Button();
      this.textBox1 = new System.Windows.Forms.TextBox();
      this.button3 = new System.Windows.Forms.Button();
      this.SuspendLayout();
      //
      // listBox1
      //
      this.listBox1.FormattingEnabled = true;
      this.listBox1.ItemHeight = 12;
      this.listBox1.Location = new System.Drawing.Point(12, 12);
      this.listBox1.Name = "listBox1";
      this.listBox1.Size = new System.Drawing.Size(268, 148);
      this.listBox1.TabIndex = 0;
      //
      // button1
      //
      this.button1.Location = new System.Drawing.Point(12, 166);
      this.button1.Name = "button1";
      this.button1.Size = new System.Drawing.Size(268, 35);
      this.button1.TabIndex = 1;
      this.button1.Text = "連接";
      this.button1.UseVisualStyleBackColor = true;
      this.button1.Click += new System.EventHandler(this.button1_Click);
      //
      // textBox1
      //
      this.textBox1.Location = new System.Drawing.Point(12, 207);
      this.textBox1.Multiline = true;
      this.textBox1.Name = "textBox1";
      this.textBox1.Size = new System.Drawing.Size(211, 54);
      this.textBox1.TabIndex = 3;
      //
      // button3
      //
      this.button3.Location = new System.Drawing.Point(229, 207);
      this.button3.Name = "button3";
      this.button3.Size = new System.Drawing.Size(51, 54);
      this.button3.TabIndex = 4;
      this.button3.Text = "發言";
      this.button3.UseVisualStyleBackColor = true;
      this.button3.Click += new System.EventHandler(this.button3_Click);
      //
      // Form1
      //
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.ClIEntSize = new System.Drawing.Size(292, 273);
      this.Controls.Add(this.button3);
      this.Controls.Add(this.textBox1);
      this.Controls.Add(this.button1);
      this.Controls.Add(this.listBox1);
      this.Name = "Form1";
      this.Text = "客戶端";
      this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Closing);
      this.Load += new System.EventHandler(this.Form1_Load);
      this.ResumeLayout(false);
      this.PerformLayout();
    }
    #endregion
    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.Button button3;
  }
}
//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.Threading;
namespace ClIEntTest
{
  public partial class Form1 : Form
  {
    Socket clIEnt;
    public string host = "";//要連接的服務器IP
    int port = 2000;
    Thread Data;
    public string nick = "";//給自己起一個昵稱,呵呵
    Encoding utf8 = Encoding.UTF8;
    Encoding gb2312 = Encoding.GetEncoding("GB2312");
    delegate void SetSafe(string text);
    public Form1()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)//連接服務器
    {
      Form2 frm2 = new Form2();
      frm2.ShowDialog();//顯示一個對話框,輸入服務器IP和自己的昵稱
      host = frm2.textBox2.Text;
      nick=frm2.textBox1.Text;
      try
      {
        clIEnt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        clIEnt.Connect(host, port);//連接服務器
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }
    private void Form1_Load(object sender, EventArgs e)//窗體載入時候開啟一個數據處理線程,處理從服務器得到的數據
    {
      Data = new Thread(new ThreadStart(DataStart));
      Data.Start();
    }
    public void DataStart()//只要能從服務器得到數據,就顯示在ListBox上,這個過程一直循環
    {
      while (true)
      {
        try
        {
          NetworkStream ns = new NetworkStream(clIEnt);
          StreamReader reader = new StreamReader(ns);
          string result =reader.ReadLine();
          byte[] u = utf8.GetBytes(result);
          byte[] gb = Encoding.Convert(utf8, gb2312, u);
          string sGb = gb2312.GetString(gb);
          AddList(sGb);
          reader.Close();
          ns.Close();
        }
        catch { }
        Thread.Sleep(1000);
      }
    }
    private void button3_Click(object sender, EventArgs e)//發言
    {
      try
      {
        string sendString = "("+ clIEnt.LocalEndPoint.ToString()+")"+nick+"說"+textBox1.Text + "\r\n";
        byte[] butf = utf8.GetBytes(sendString);
        clIEnt.Send(butf);//按照昵稱(IP)說的話的格式發送給服務器
      }
      catch { }
    }
    private void AddList(object text)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (this.listBox1.InvokeRequired)
      {
        SetSafe d = new SetSafe(AddList);
        this.Invoke(d, new object[] { text });
      }
      else
      {
        this.listBox1.Items.Add(text);
      }
    }
    private void Closing(object sender, System.EventArgs e)//斷開連接,發送服務器"Close"信息
    {
      try
      {
        Data.Abort();
        Byte[] buf = System.Text.Encoding.UTF8.GetBytes("Close" + "\r\n");
        clIEnt.Send(buf);
      }
      catch { }
    }
  }
}
//Form2.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ClIEntTest
{
  public partial class Form2 : Form
  {
    public Form2()
    {
      InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
      this.Hide();
     
    }
  }
}
服務端
// Form1.Designer.cs
namespace ServerTest
{
  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.listBox1 = new System.Windows.Forms.ListBox();
      this.button2 = new System.Windows.Forms.Button();
      this.SuspendLayout();
      //
      // button1
      //
      this.button1.Location = new System.Drawing.Point(12, 12);
      this.button1.Name = "button1";
      this.button1.Size = new System.Drawing.Size(130, 44);
      this.button1.TabIndex = 0;
      this.button1.Text = "開啟服務";
      this.button1.UseVisualStyleBackColor = true;
      this.button1.Click += new System.EventHandler(this.button1_Click);
      //
      // listBox1
      //
      this.listBox1.FormattingEnabled = true;
      this.listBox1.ItemHeight = 12;
      this.listBox1.Location = new System.Drawing.Point(12, 62);
      this.listBox1.Name = "listBox1";
      this.listBox1.Size = new System.Drawing.Size(268, 196);
      this.listBox1.TabIndex = 1;
      //
      // button2
      //
      this.button2.Location = new System.Drawing.Point(150, 12);
      this.button2.Name = "button2";
      this.button2.Size = new System.Drawing.Size(130, 44);
      this.button2.TabIndex = 2;
      this.button2.Text = "T人";
      this.button2.UseVisualStyleBackColor = true;
      this.button2.Click += new System.EventHandler(this.button2_Click);
      //
      // Form1
      //
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.ClIEntSize = new System.Drawing.Size(292, 273);
      this.Controls.Add(this.button2);
      this.Controls.Add(this.listBox1);
      this.Controls.Add(this.button1);
      this.Name = "Form1";
      this.Text = "服務端";
      this.ResumeLayout(false);
      this.FormClosing+=new System.Windows.Forms.FormClosingEventHandler(Closing);
    }
    #endregion
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.ListBox listBox1;
    private System.Windows.Forms.Button button2;
  }
}
//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.Threading;
using System.IO;
using System.Net.Sockets;
using System.Collections;
namespace ServerTest
{
  public partial class Form1 : Form
  {
    int port = 2000;//綁定本機端口2000
    TcpListener listener;
    delegate void SetSafe(string text);
    ArrayList conList=new ArrayList();
    Encoding utf8 = Encoding.UTF8;
    Encoding gb2312 = Encoding.GetEncoding("GB2312");
    Thread listenerThread;
    Thread DataThread;
    public Form1()
    {
      InitializeComponent();
    }
    public void AcceptRequest() //連接處理線程
    {
      try
      {
        while (true)
        {
          if (listener.Pending())//是否有等待連接隊列
          {
            Socket s = listener.AcceptSocket();//建立連接
            conList.Add(s);//添加當前連接到已連接列表
            if (s.Connected)
            {
              string ServerEndPoint = "歡迎登陸服務器" + s.LocalEndPoint.ToString() + "\r\n";
              byte[] bgb = gb2312.GetBytes(ServerEndPoint);
              byte[] butf = Encoding.Convert(gb2312, utf8, bgb);
              s.Send(butf);//發送歡迎登陸信息
              string mpoint = s.RemoteEndPoint.ToString();
              AddList(mpoint);//把當前客戶端IP,Port添加到ListBox顯示
            }
          }
        }
      }
      catch { }
      Thread.Sleep(1000);
    }
    public void ReceiveData()//數據處理線程
    {
        while (true)
        {
          try
          {
            ArrayList CloseSocketList = new ArrayList();//關閉連接列表
            CloseSocketList.Clear();//清空關閉連接列表
            foreach (Socket s in conList)//循環每一個已建立的連接
            {
              NetworkStream ns = new NetworkStream(s);
              StreamReader reader = new StreamReader(ns);
              if (ns.DataAvailable)
              {
                string result = reader.ReadLine();
                byte[] u = utf8.GetBytes(result);
                byte[] gb = Encoding.Convert(utf8, gb2312, u);
                string sGb = gb2312.GetString(gb);
                if (sGb.StartsWith("Close"))//如果收到Close信息
                {
                  CloseSocketList.Add(s);//把當前連接添加到關閉連接列表
                }
                else
                {
                  foreach (Socket p in conList)//把從一個連接得到的信息發給所有的連接的客戶端,就好比聊天室的聊天大廳,公共聊天
                  {
                    string sendString = result + "\r\n";
                    byte[] butf = utf8.GetBytes(sendString);
                    p.Send(butf);
                  }
                }
              }
              reader.Close();
              ns.Close();
            }
            foreach (Socket s in CloseSocketList)//關閉關閉連接列表裡面的連接
            {
              DelList(s.RemoteEndPoint.ToString());//從ListBox刪除關閉的連接
              s.Close();
              conList.Remove(s);
            }
          }
          catch { }
          Thread.Sleep(1000);
        }
    }
    private void button1_Click(object sender, EventArgs e)//啟動服務器
    {
      listener = new TcpListener(port);//開啟2000端口的監聽
      listener.Start();
      listenerThread = new Thread(new ThreadStart(AcceptRequest));//啟動連接處理線程
      listenerThread.Start();
      DataThread = new Thread(new ThreadStart(ReceiveData));//啟動數據處理線程
      DataThread.Start();
    }
    private void AddList(object text)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (this.listBox1.InvokeRequired)
      {
        SetSafe d = new SetSafe(AddList);
        this.Invoke(d, new object[] { text });
      }
      else
      {
        this.listBox1.Items.Add(text);
      }
    }
    private void DelList(object text)
    {
      // InvokeRequired required compares the thread ID of the
      // calling thread to the thread ID of the creating thread.
      // If these threads are different, it returns true.
      if (this.listBox1.InvokeRequired)
      {
        SetSafe d = new SetSafe(DelList);
        this.Invoke(d, new object[] { text });
      }
      else
      {
        this.listBox1.Items.Remove(text);
      }
    }
    private void button2_Click(object sender, EventArgs e)//踢指定的客戶端連接
    {
      try
      {
        string temp = listBox1.SelectedItem.ToString();//選擇要踢的客戶端
        DelList(temp);//ListBox刪除它
        foreach (Socket f in conList)
        {
          if ((f.RemoteEndPoint.ToString()) == temp)//找到那個要踢的客戶端
          {
            string Message = "你被服務器T了" + "\r\n";
            byte[] bgb = gb2312.GetBytes(Message);
            byte[] butf = Encoding.Convert(gb2312, utf8, bgb);
            f.Send(butf);//告訴他他被踢了
            conList.Remove(f);//把它從已經連接列表中刪除,斷開連接
            f.Close();
          }
        }
      }
      catch { }
    }
    private void Closing(object sender, EventArgs e)//窗體關閉,斷開所有連接,關閉所有線程
    {
      try
      {
        foreach (Socket o in conList)
        {
          o.Close();
        }
        listenerThread.Abort();
        DataThread.Abort();
      }
      catch { }
    }
  }
}
這個例子比較簡單,實際在使用中會比較復雜,比如說我們的服務端要實現很多功能,舉個網絡游戲的例子,你要行走,要攻擊,要加血,要回藍,這每一個動作都對應一個命令,是以命令+內容+結束符的格式傳送給服務器的,服務器在接收到信息,再對信息分類處理。下面我看一個這樣的例子,是一個FTP的例子。客戶端可以顯示服務器的文件列表,可以選擇要下載的文件,可以上傳文件,服務器可以顯示客戶端的連接IP,可以斷開指定的客戶端。
客戶端
//Form1.Designer.Cs
namespace FTPClIEntTest
{
  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.listBox1 = new System.Windows.Forms.ListBox();
      this.button1 = new System.Windows.Forms.Button();
      this.button2 = new System.Windows.Forms.Button();
      this.button3 = new System.Windows.Forms.Button();
      this.button4 = new System.Windows.Forms.Button();
      this.button5 = new System.Windows.Forms.Button();
      this.SuspendLayout();
      //
      // listBox1
      //
      this.listBox1.FormattingEnabled = true;
      this.listBox1.ItemHeight = 12;
      this.listBox1.Location = new System.Drawing.Point(11, 9);
      this.listBox1.Name = "listBox1";
      this.listBox1.Size = new System.Drawing.Size(271, 160);
      this.listBox1.TabIndex = 0;
      //
      // button1
      //
      this

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved