DotNET(C#) Socket基本編程 )

來源:互聯網
上載者:User
http://blog.csdn.net/itfly8/archive/2006/03/13/622877.aspx

Socket基本編程

服務端:

using System.Net;

using System.Net.Sockets;

using System.Text;

using System.Threading;

 

Thread mythread ;

Socket socket;

// 清理所有正在使用的資源。

protected override void Dispose( bool disposing )

{

try

  {   

   socket.Close();//釋放資源

   mythread.Abort ( ) ;//中止線程

  }

  catch{ }

 

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

public static IPAddress GetServerIP()

{

IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName());

return ieh.AddressList[0];

}

private void BeginListen()

{

IPAddress ServerIp=GetServerIP();

IPEndPoint iep=new IPEndPoint(ServerIp,8000);

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

 

byte[] byteMessage=new byte[100];

this.label1.Text=iep.ToString();

socket.Bind(iep);

// do

while(true)

{

try

{

socket.Listen(5);

Socket newSocket=socket.Accept();

newSocket.Receive(byteMessage);

 

string sTime = DateTime.Now.ToShortTimeString ( ) ;

string msg=sTime+":"+"Message from:";

msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);

this.listBox1.Items.Add(msg);

 

}

catch(SocketException ex)

{

this.label1.Text+=ex.ToString();

}

}

// while(byteMessage!=null);

}

//開始監聽

private void button1_Click(object sender, System.EventArgs e)

{

try

{

mythread = new Thread(new ThreadStart(BeginListen));

mythread.Start();

 

}

catch(System.Exception er)

{

MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,MessageBoxIcon.Stop);

}

}

 

 

用戶端:

 

using System.Net;

using System.Net.Sockets;

using System.Text;

 

private void button1_Click(object sender, System.EventArgs e)

{

BeginSend();

}

private void BeginSend()

{

string ip=this.txtip.Text;

string port=this.txtport.Text;

 

IPAddress serverIp=IPAddress.Parse(ip);

int serverPort=Convert.ToInt32(port);

IPEndPoint iep=new IPEndPoint(serverIp,serverPort);

byte[] byteMessage;

// do

// {

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

socket.Connect(iep);

 

byteMessage=Encoding.ASCII.GetBytes(textBox1.Text);

socket.Send(byteMessage);

socket.Shutdown(SocketShutdown.Both);

socket.Close();

// }

// while(byteMessage!=null);

}

 

基於TCP協議的發送和接收端

 

TCP協議的接收端

 

using System.Net.Sockets ; //使用到TcpListen類

using System.Threading ; //使用到線程

using System.IO ; //使用到StreamReader類

 

int port = 8000; //定義偵聽連接埠號碼

private Thread thThreadRead; //建立線程,用以偵聽連接埠號碼,接收資訊

private TcpListener tlTcpListen; //偵聽連接埠號碼

private bool blistener = true; //設定標示位,判斷偵聽狀態

private NetworkStream nsStream; //建立接收的基本資料流

private StreamReader srRead;

private System.Windows.Forms.StatusBar statusBar1;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.ListBox listBox1; //從網路基礎資料流中讀取資料

private TcpClient tcClient ;

 

private void Listen ( )

{

try

{

tlTcpListen = new TcpListener ( port ) ; //以8000連接埠號碼來初始化TcpListener執行個體

tlTcpListen.Start ( ) ; //開始監聽

statusBar1.Text = "正在監聽..." ;

tcClient = tlTcpListen.AcceptTcpClient ( ) ; //通過TCP串連請求

nsStream = tcClient.GetStream ( ) ; //擷取用以發送、接收資料的網路基礎資料流

srRead=new StreamReader(nsStream);//以得到的網路基礎資料流來初始化StreamReader執行個體

statusBar1.Text = "已經串連!";

 

while( blistener ) //迴圈偵聽

{

string sMessage = srRead.ReadLine();//從網路基礎資料流中讀取一行資料

if ( sMessage == "STOP" ) //判斷是否為斷開TCP串連控制碼

{

tlTcpListen.Stop(); //關閉偵聽

nsStream.Close(); //釋放資源

srRead.Close();

statusBar1.Text = "串連已經關閉!" ;

thThreadRead.Abort(); //中止線程

return;

}

 

string sTime = DateTime.Now.ToShortTimeString ( ) ; //擷取接收資料時的時間

listBox1.Items.Add ( sTime + " " + sMessage ) ;

}

}

catch ( System.Security.SecurityException )

{

MessageBox.Show ( "偵聽失敗!" , "錯誤" ) ;

}

}

//開始監聽

private void button1_Click(object sender, System.EventArgs e)

{

thThreadRead = new Thread ( new ThreadStart ( Listen ) );

thThreadRead.Start();//啟動線程

button1.Enabled=false;

}

// 清理所有正在使用的資源。

protected override void Dispose( bool disposing )

{

try

{

tlTcpListen.Stop(); //關閉偵聽

nsStream.Close();

srRead.Close();//釋放資源

thThreadRead.Abort();//中止線程

}

catch{}

 

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

 

TCP協議的發送端

 

using System.Net.Sockets; //使用到TcpListen類

using System.Threading; //使用到線程

using System.IO; //使用到StreamWriter類

using System.Net; //使用IPAddress類、IPHostEntry類等

 

private StreamWriter swWriter; //用以向網路基礎資料流傳送資料 

private NetworkStream nsStream; //建立發送資料的網路基礎資料流 

private TcpClient tcpClient;

private System.Windows.Forms.Button button1;

private System.Windows.Forms.TextBox textBox1;

private System.Windows.Forms.Button button2;

private System.Windows.Forms.TextBox textBox2;

private System.Windows.Forms.StatusBar statusBar1;

private System.Windows.Forms.Label label1;

private System.Windows.Forms.Label label2; //通過它實現向遠程主機提出TCP串連申請 

private bool tcpConnect = false; //定義標識符,用以表示TCP串連是否建立

 

//串連 

private void button1_Click(object sender, System.EventArgs e)

{

IPAddress ipRemote ;

try

{

ipRemote = IPAddress.Parse ( textBox1.Text ) ;

}

catch //判斷給定的IP地址的合法性

{

MessageBox.Show ( "輸入的IP地址不合法!" , "錯誤提示!" ) ;

return ;

}

 

IPHostEntry ipHost ;

try

{

ipHost = Dns.Resolve ( textBox1.Text ) ; 

}

catch //判斷IP地址對應主機是否線上

{

MessageBox.Show ("遠程主機不線上!" , "錯誤提示!" ) ;

return ;

}

 

string sHostName = ipHost.HostName ;

try

{

TcpClient tcpClient = new TcpClient(sHostName,8000);//對遠程主機的8000連接埠提出TCP串連申請

nsStream = tcpClient.GetStream();//通過申請,並擷取傳送資料的網路基礎資料流  

swWriter = new StreamWriter(nsStream);//使用擷取的網路基礎資料流來初始化StreamWriter執行個體

button1.Enabled = false ;

button2.Enabled = true ;

tcpConnect = true ;

statusBar1.Text = "已經串連!" ;

}

catch

{

MessageBox.Show ( "無法和遠程主機8000連接埠建立串連!" , "錯誤提示!" ) ;

return ;

}

}

 

//發送

private void button2_Click(object sender, System.EventArgs e)

{

if (textBox2.Text !="")

{

swWriter.WriteLine(textBox2.Text);//重新整理當前資料流中的資料

swWriter.Flush();

}

else

{

MessageBox.Show("發送資訊不可為空!","錯誤提示!");

}

}

// 清理所有正在使用的資源。

protected override void Dispose( bool disposing )

{

if ( tcpConnect )

{

swWriter.WriteLine ( "STOP" ) ; //發送控制碼  

swWriter.Flush (); //重新整理當前資料流中的資料  

nsStream.Close (); //清除資源

swWriter.Close ();

}

if( disposing )

{

if (components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

相關文章

聯繫我們

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