熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

C#Socket基本編程

2013-11-13 10:04:11  來源: .NET編程 

  view plainprint?

  //Socket基本編程

  //服務端

  using SystemNet

  using SystemNetSockets

  using SystemText

  using SystemThreading

  Thread mythread

  Socket socket

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

  protected override void Dispose( bool disposing )

  {

  try

  {

  socketClose()//釋放資源

  mythreadAbort ( ) //中止線程

  }

  catch{ }

  if( disposing )

  {

  if (components != null)

  {

  componentsDispose()

  }

  }

  baseDispose( disposing )

  }

  public static IPAddress GetServerIP()

  {

  IPHostEntry ieh=DnsGetHostByName(DnsGetHostName())

  return iehAddressList[]

  }

  private void BeginListen()

  {

  IPAddress ServerIp=GetServerIP()

  IPEndPoint iep=new IPEndPoint(ServerIp

  socket=new Socket(AddressFamilyInterNetworkSocketTypeStreamProtocolTypeTcp)

  byte[] byteMessage=new byte[]

  thislabelText=iepToString()

  socketBind(iep)

  // do

  while(true)

  {

  try

  {

  socketListen(

  Socket newSocket=socketAccept()

  newSocketReceive(byteMessage)

  string sTime = DateTimeNowToShortTimeString ( )

  string msg=sTime++Message from

  msg+=newSocketRemoteEndPointToString()+EncodingDefaultGetString(byteMessage)

  thislistBoxItemsAdd(msg)

  }

  catch(SocketException ex)

  {

  thislabelText+=exToString()

  }

  }

  // while(byteMessage!=null)

  }

  //開始監聽

  private void button_Click(object sender SystemEventArgs e)

  {

  try

  {

  mythread = new Thread(new ThreadStart(BeginListen))

  mythreadStart()

  }

  catch(SystemException er)

  {

  MessageBoxShow(erMessage完成MessageBoxButtonsOKMessageBoxIconStop)

  }

  }

  //客戶端

  using SystemNet

  using SystemNetSockets

  using SystemText

  private void button_Click(object sender SystemEventArgs e)

  {

  BeginSend()

  }

  private void BeginSend()

  {

  string ip=thistxtipText

  string port=thistxtportText

  IPAddress serverIp=IPAddressParse(ip)

  int serverPort=ConvertToInt(port)

  IPEndPoint iep=new IPEndPoint(serverIpserverPort)

  byte[] byteMessage

  // do

  // {

  Socket socket=new Socket(AddressFamilyInterNetworkSocketTypeStreamProtocolTypeTcp)

  socketConnect(iep)

  byteMessage=EncodingASCIIGetBytes(textBoxText)

  socketSend(byteMessage)

  socketShutdown(SocketShutdownBoth)

  socketClose()

  // }

  // while(byteMessage!=null)

  }

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

  TCP協議的接收端

  using SystemNetSockets //使用到TcpListen類

  using SystemThreading //使用到線程

  using SystemIO //使用到StreamReader類

  int port = //定義偵聽端口號

  private Thread thThreadRead //創建線程用以偵聽端口號接收信息

  private TcpListener tlTcpListen //偵聽端口號

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

  private NetworkStream nsStream //創建接收的基本數據流

  private StreamReader srRead

  private SystemWindowsFormsStatusBar statusBar

  private SystemWindowsFormsButton button

  private SystemWindowsFormsListBox listBox //從網絡基礎數據流中讀取數據

  private TcpClient tcClient

  private void Listen ( )

  {

  try

  {

  tlTcpListen = new TcpListener ( port ) //以端口號來初始化TcpListener實例

  tlTcpListenStart ( ) //開始監聽

  statusBarText = 正在監聽

  tcClient = tlTcpListenAcceptTcpClient ( ) //通過TCP連接請求

  nsStream = tcClientGetStream ( ) //獲取用以發送接收數據的網絡基礎數據流

  srRead=new StreamReader(nsStream)//以得到的網絡基礎數據流來初始化StreamReader實例

  statusBarText = 已經連接!

  while( blistener ) //循環偵聽

  {

  string sMessage = srReadReadLine()//從網絡基礎數據流中讀取一行數據

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

  {

  tlTcpListenStop() //關閉偵聽

  nsStreamClose() //釋放資源

  srReadClose()

  statusBarText = 連接已經關閉!

  thThreadReadAbort() //中止線程

  return

  }

  string sTime = DateTimeNowToShortTimeString ( ) //獲取接收數據時的時間

  listBoxItemsAdd ( sTime + + sMessage )

  }

  }

  catch ( SystemSecuritySecurityException )

  {

  MessageBoxShow ( 偵聽失敗! 錯誤

  }

  }

  //開始監聽

  private void button_Click(object sender SystemEventArgs e)

  {

  thThreadRead = new Thread ( new ThreadStart ( Listen ) )

  thThreadReadStart()//啟動線程

  buttonEnabled=false

  }

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

  protected override void Dispose( bool disposing )

  {

  try

  {

  tlTcpListenStop() //關閉偵聽

  nsStreamClose()

  srReadClose()//釋放資源

  thThreadReadAbort()//中止線程

  }

  catch{}

  if( disposing )

  {

  if (components != null)

  {

  componentsDispose()

  }

  }

  baseDispose( disposing )

  }

  TCP協議的發送端

  using SystemNetSockets //使用到TcpListen類

  using SystemThreading //使用到線程

  using SystemIO //使用到StreamWriter類

  using SystemNet //使用IPAddress類IPHostEntry類等

  private StreamWriter swWriter //用以向網絡基礎數據流傳送數據

  private NetworkStream nsStream //創建發送數據的網絡基礎數據流

  private TcpClient tcpClient

  private SystemWindowsFormsButton button

  private SystemWindowsFormsTextBox textBox

  private SystemWindowsFormsButton button

  private SystemWindowsFormsTextBox textBox

  private SystemWindowsFormsStatusBar statusBar

  private SystemWindowsFormsLabel label

  private SystemWindowsFormsLabel label //通過它實現向遠程主機提出TCP連接申請

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

  //連接

  private void button_Click(object sender SystemEventArgs e)

  {

  IPAddress ipRemote

  try

  {

  ipRemote = IPAddressParse ( textBoxText )

  }

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

  {

  MessageBoxShow ( 輸入的IP地址不合法! 錯誤提示!

  return

  }

  IPHostEntry ipHost

  try

  {

  ipHost = DnsResolve ( textBoxText )

  }

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

  {

  MessageBoxShow (遠程主機不在線! 錯誤提示!

  return

  }

  string sHostName = ipHostHostName

  try

  {

  TcpClient tcpClient = new TcpClient(sHostName//對遠程主機的端口提出TCP連接申請

  nsStream = tcpClientGetStream()//通過申請並獲取傳送數據的網絡基礎數據流

  swWriter = new StreamWriter(nsStream)//使用獲取的網絡基礎數據流來初始化StreamWriter實例

  buttonEnabled = false

  buttonEnabled = true

  tcpConnect = true

  statusBarText = 已經連接!

  }

  catch

  {

  MessageBoxShow ( 無法和遠程主機端口建立連接! 錯誤提示!

  return

  }

  }

  //發送

  private void button_Click(object sender SystemEventArgs e)

  {

  if (textBoxText !=

  {

  swWriterWriteLine(textBoxText)//刷新當前數據流中的數據

  swWriterFlush()

  }

  else

  {

  MessageBoxShow(發送信息不能為空!錯誤提示!

  }

  }

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

  protected override void Dispose( bool disposing )

  {

  if ( tcpConnect )

  {

  swWriterWriteLine ( STOP //發送控制碼

  swWriterFlush () //刷新當前數據流中的數據

  nsStreamClose () //清除資源

  swWriterClose ()

  }

  if( disposing )

  {

  if (components != null)

  {

  componentsDispose()

  }

  }

  baseDispose( disposing )

  }

  

  資料引用


From:http://tw.wingwit.com/Article/program/net/201311/12468.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.