採用UDP廣播模式寫簡單資訊傳輸工具~

來源:互聯網
上載者:User
使用UDPClient類
這個是我寫的測試代碼,供參考~

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

namespace UDPWinTest
{
/// <summary>
/// Form1 的摘要說明。
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button btnStart;
private System.Windows.Forms.Button btnJoin;
private System.Windows.Forms.TextBox txtServerIP;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox txtMsgSend;
private System.Windows.Forms.TextBox txtMessageMain;
/// <summary>
/// 必需的設計器變數。
/// </summary>
private System.ComponentModel.Container components = null;

private static UdpClient m_Client;

private static int ListenerPort = 80;
private static int SenderPort = 80;
private static int LocalPort;
private static int RemotePort;

private static string m_szHostName;

private static IPAddress m_GroupAddress;
private static IPHostEntry m_LocalHost;
private static IPEndPoint m_RemoteEP;
private System.Windows.Forms.Button btnEnd;

private static bool m_Done = false;
private System.Windows.Forms.Button btnClose;

private Thread t = null ;
private Thread t2 = null ;

public Form1()
{
InitializeComponent();
}

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

#region Windows 表單設計器產生的程式碼
/// <summary>
/// 設計器支援所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內容。
/// </summary>
private void InitializeComponent()
{
this.btnStart = new System.Windows.Forms.Button();
this.btnJoin = new System.Windows.Forms.Button();
this.txtServerIP = new System.Windows.Forms.TextBox();
this.txtMessageMain = new System.Windows.Forms.TextBox();
this.txtMsgSend = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.btnEnd = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnStart
//
this.btnStart.Location = new System.Drawing.Point(16, 16);
this.btnStart.Name = "btnStart";
this.btnStart.TabIndex = 0;
this.btnStart.Text = "Start";
this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
//
// btnJoin
//
this.btnJoin.Location = new System.Drawing.Point(408, 16);
this.btnJoin.Name = "btnJoin";
this.btnJoin.TabIndex = 1;
this.btnJoin.Text = "Join";
this.btnJoin.Click += new System.EventHandler(this.btnJoin_Click);
//
// txtServerIP
//
this.txtServerIP.Location = new System.Drawing.Point(304, 16);
this.txtServerIP.Name = "txtServerIP";
this.txtServerIP.Size = new System.Drawing.Size(96, 21);
this.txtServerIP.TabIndex = 2;
this.txtServerIP.Text = "10.89.58.220";
//
// txtMessageMain
//
this.txtMessageMain.Location = new System.Drawing.Point(16, 48);
this.txtMessageMain.Multiline = true;
this.txtMessageMain.Name = "txtMessageMain";
this.txtMessageMain.Size = new System.Drawing.Size(464, 184);
this.txtMessageMain.TabIndex = 3;
this.txtMessageMain.Text = "";
//
// txtMsgSend
//
this.txtMsgSend.Location = new System.Drawing.Point(16, 240);
this.txtMsgSend.Name = "txtMsgSend";
this.txtMsgSend.Size = new System.Drawing.Size(384, 21);
this.txtMsgSend.TabIndex = 4;
this.txtMsgSend.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(408, 240);
this.button1.Name = "button1";
this.button1.TabIndex = 5;
this.button1.Text = "Send";
this.button1.Click += new System.EventHandler(this.Send_Click);
//
// btnEnd
//
this.btnEnd.Location = new System.Drawing.Point(112, 16);
this.btnEnd.Name = "btnEnd";
this.btnEnd.TabIndex = 6;
this.btnEnd.Text = "End";
this.btnEnd.Click += new System.EventHandler(this.btnEnd_Click);
//
// btnClose
//
this.btnClose.Location = new System.Drawing.Point(208, 16);
this.btnClose.Name = "btnClose";
this.btnClose.TabIndex = 7;
this.btnClose.Text = "Close";
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(504, 273);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnEnd);
this.Controls.Add(this.button1);
this.Controls.Add(this.txtMsgSend);
this.Controls.Add(this.txtMessageMain);
this.Controls.Add(this.txtServerIP);
this.Controls.Add(this.btnJoin);
this.Controls.Add(this.btnStart);
this.Name = "Form1";
this.Text = "UDPWinTest";
this.ResumeLayout(false);

}
#endregion

/// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void btnStart_Click(object sender, System.EventArgs e)
{
LocalPort = SenderPort;
RemotePort = ListenerPort;

m_szHostName = Dns.GetHostName();
m_LocalHost = Dns.GetHostByName(m_szHostName);

AddToMain("Local Port: " + LocalPort + ", Remote: " + RemotePort);
AddToMain("Initializing...");

string LocalHostIP = m_LocalHost.AddressList[0].ToString();
string[] ArrIP = LocalHostIP.Split(new char[]{'.'});
LocalHostIP = "224" + "." + ArrIP[1] + "." + ArrIP[2] + "." + ArrIP[3];

Initialize(LocalHostIP);

AddToMain("Starting Listener thread..." );

//開始新線程
t = new Thread(new ThreadStart(Listener)); //偵聽線程
t.Start();

this.btnJoin.Enabled = false;
this.btnStart.Enabled = false;

}

private void btnJoin_Click(object sender, System.EventArgs e)
{
LocalPort = SenderPort;
RemotePort = ListenerPort;

m_szHostName = Dns.GetHostName();
m_LocalHost = Dns.GetHostByName(m_szHostName);

AddToMain("Local Port: " + LocalPort + ", Remote: " + RemotePort);
AddToMain("Initializing...");

string ServerIP = this.txtServerIP.Text;
string[] ArrIP = ServerIP.Split(new char[]{'.'});
ServerIP = "224" + "." + ArrIP[1] + "." + ArrIP[2] + "." + ArrIP[3];

Initialize(ServerIP);

AddToMain("Starting Listener thread...");

//開始新線程
t = new Thread(new ThreadStart(Listener)); //偵聽線程
t.Start();

this.btnStart.Enabled = false;
this.btnJoin.Enabled = false;
}

private void Send_Click(object sender, System.EventArgs e)
{
//開始新線程
t2 = new Thread(new ThreadStart(Send)); //偵聽線程
t2.Start();
}

/// <summary>
///
/// </summary>
public void Send()
{
Thread.Sleep(1000);

Byte [] buffer = null;

System.Text.Encoding ASCII = System.Text.Encoding.ASCII;

String s = this.txtMsgSend.Text ;

if( s.Length == 0 )
return ;

if(String.Compare(s,0,"@",0,1,true,CultureInfo.InvariantCulture) == 0)
{
m_Done = true;
s = m_szHostName + ":@";
Application.Exit();
}
else
{
s = m_szHostName + ":" + s;
}


buffer = new Byte[s.Length + 1];

int len = ASCII.GetBytes( s.ToCharArray(), 0, s.Length, buffer, 0);

int ecode = m_Client.Send(buffer, len, m_RemoteEP);

if(ecode <= 0)
{
AddToMain("Error in send : " + ecode);
}

t2.Abort();

}

public static void Terminate()
{
m_Client.DropMulticastGroup(m_GroupAddress);
}

/// <summary>
/// 初始化
/// </summary>
public void Initialize(string IP)
{

m_Client = new UdpClient(LocalPort);

//設定廣播組的網路地址
m_GroupAddress = IPAddress.Parse(IP);

try
{ //加入廣播組
m_Client.JoinMulticastGroup(m_GroupAddress, 100);
}
catch(Exception ex)
{
string mm = ex.Message ;
AddToMain("Unable to join multicast group" + ex.Message);
}

//設定網路端點
m_RemoteEP = new IPEndPoint( m_GroupAddress, RemotePort );

}

/// <summary>
///
/// </summary>
public void Listener()
{

Thread.Sleep(2000);

System.Text.Encoding ASCII = System.Text.Encoding.ASCII;


while(!m_Done)
{
IPEndPoint endpoint = null;
Byte[] data = m_Client.Receive(ref endpoint);

String strData = ASCII.GetString(data);

if( strData.IndexOf(":@") > 0 )
{
Char [] separators = {':'};
String [] vars = strData.Split(separators);

if( vars[0] == m_szHostName ) //主系統已關閉
{
AddToMain("shutting down Listener thread...");
m_Done = true;
}
else
{
AddToMain( vars[0] + " has left the conversation");
}
}
else
{
if(strData.IndexOf(":") > 0)
{
Char [] separators = {':'};
String [] vars = strData.Split(separators);

if( vars[0] != m_szHostName )
{
AddToMain(strData);
}
else
{
AddToMain(strData);
}
}
}
}
t.Abort();

AddToMain("Listener thread finished...");
return;
}

private void AddToMain(string _Message)
{
this.txtMessageMain.Text = this.txtMessageMain.Text + _Message + "\r\n";
}

private void btnEnd_Click(object sender, System.EventArgs e)
{
this.btnStart.Enabled = true;
this.btnJoin.Enabled = true;

try
{
t.Abort();
t.Interrupt();
t2.Abort();
t2.Interrupt();

AddToMain("Closing connection...");

m_Client.DropMulticastGroup(m_GroupAddress);
}
catch
{}


//Terminate();
}

private void btnClose_Click(object sender, System.EventArgs e)
{
try
{
t.Abort();
t.Interrupt();
t2.Abort();
t2.Interrupt();
Terminate() ;
}
catch
{}
Application.Exit();
}
}
}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.