程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#中Socket通訊用法實例詳解

C#中Socket通訊用法實例詳解

編輯:C#入門知識

C#中Socket通訊用法實例詳解。本站提示廣大學習愛好者:(C#中Socket通訊用法實例詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中Socket通訊用法實例詳解正文


本文實例講述了C#中Socket通訊用法。分享給年夜家供年夜家參考。詳細以下:

1、UDP方法:

辦事器端代碼:

static void Main(string[] args)
{
  int recv;
  byte[] data = new byte[1024];
  IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//界說一收集端點
  Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//界說一個Socket
  newsock.Bind(ipep);//Socket與當地的一個終結點相干聯
  Console.WriteLine("Waiting for a client..");
  IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);//界說要發送的盤算機的地址
  EndPoint Remote = (EndPoint)(sender);//
  recv = newsock.ReceiveFrom(data, ref Remote);//接收數據      
  Console.WriteLine("Message received from{0}:", Remote.ToString());
  Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
  string welcome = "Welcome to my test server!";
  data = Encoding.ASCII.GetBytes(welcome);
  newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
  while (true)
  {
    data = new byte[1024];
    recv = newsock.ReceiveFrom(data, ref Remote);
    Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
    newsock.SendTo(data, recv, SocketFlags.None, Remote);
  }
}

客戶端代碼:

void MainInfo()
{
  byte[] data = new byte[1024];//界說一個數組用來做數據的緩沖區
  string input, stringData;
  IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("192.168.1.21"), 9050);
  Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  string welcome = "Hello,are you there?";
  data = Encoding.ASCII.GetBytes(welcome);
  server.SendTo(data, data.Length, SocketFlags.None, ipep);//將數據發送到指定的終結點
  IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
  EndPoint Remote = (EndPoint)sender;
  data = new byte[1024];
  int recv = server.ReceiveFrom(data, ref Remote);//接收來自辦事器的數據
  Console.WriteLine("Message received from{0}:", Remote.ToString());
  Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
  while (true)//讀取數據
  {
    input = richTextBox1.Text;//從鍵盤讀取數據
    if (input == "text")//停止標志
    {
      break;
    }
    server.SendTo(Encoding.ASCII.GetBytes(input), Remote);//將數據發送到指定的終結點Remote
    data = new byte[1024];
    recv = server.ReceiveFrom(data, ref Remote);//從Remote接收數據
    stringData = Encoding.ASCII.GetString(data, 0, recv);
    Console.WriteLine(stringData);
  }
  Console.WriteLine("Stopping client");
  server.Close();
}

2、TCP方法:

辦事器端代碼:

Socket serverSocket = null;
Thread clientThread = null;
Socket clientSocket = null;
Thread thread = null;
IPAddress ips = null;
PEndPoint ipep = null;
void ServerStart()
{
  ips = Dns.GetHostAddresses(Dns.GetHostName())[0];
  //創立IPEndPoint實例  
  ipep = new IPEndPoint(ips, 9050);
  //創立一個套接字  
  serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  //將所創立的套接字與IPEndPoint綁定  
  serverSocket.Bind(ipep);
  //設置套接字為收聽形式  
  serverSocket.Listen(20);
  while (listenalive)
  {
    try
    {
      //在套接字上吸收接入的銜接  
      clientSocket = serverSocket.Accept();
      clientThread = new Thread(new ParameterizedThreadStart(ReceiveData));
      clientThread.Start(clientSocket);
    }
    catch (Exception ex)
    {
      WriteErrorLog(ex.Message);
      serverSocket.Close();
      serverSocket = null;
    }
  }
}
static void ReceiveData(object obj)
{
  bool keepalive = true;
  Socket s = obj as Socket;
  Byte[] buffer = new Byte[1024];
  //依據收聽到的客戶端套接字向客戶端發送信息  
  IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;
  Console.WriteLine("客戶端ip:" + clientep.Address + " 端口:" + clientep.Port);
  string welcome = "銜接辦事器勝利";
  buffer = System.Text.Encoding.Unicode.GetBytes(welcome);
  //向客戶端發送“銜接辦事器勝利”新聞
  s.Send(buffer, buffer.Length, SocketFlags.None);
  buffer = new Byte[1024];
  int bufLen = 0;
  string content = string.Empty;
  while (true)
  {
    //在套接字上吸收客戶端發送的信息  
    bufLen = 0;
    try
    {
      bufLen = s.Receive(buffer);
      if (bufLen == 0)
      {
        break;
      }
      content += System.Text.Encoding.Unicode.GetString(buffer, 0, bufLen);
    }
    catch (Exception ex)
    {
      break; ;
    }
  }
  Send(s, content);
  s = null;
  buffer = null;
  clientep = null;
  Thread.CurrentThread.Abort();
}

客戶端代碼:

void Send(string content)
{
  byte[] data = new byte[1024];
  newclient = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  ie = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ipadd), port);//辦事器的IP和端口
  try
  {
    //由於客戶端只是用來向特定的辦事器發送信息,所以不須要綁定本機的IP和端口。不須要監聽。
    newclient.Connect(ie);
  }
  catch (System.Net.Sockets.SocketException e)
  {
    Console.WriteLine(e.ToString());
    return;
  }
  int recv = newclient.Receive(data);
  //銜接辦事器勝利
  string stringdata = System.Text.Encoding.Unicode.GetString(data, 0, recv);
  if (stringdata == "銜接辦事器勝利")
  {
    newclient.Send(System.Text.Encoding.Unicode.GetBytes(content));
    newclient.Shutdown(System.Net.Sockets.SocketShutdown.Send);
    data = new byte[1024];
    recv = newclient.Receive(data);
    string result = System.Text.Encoding.Unicode.GetString(data, 0, recv);     
    newclient.Shutdown(System.Net.Sockets.SocketShutdown.Receive);
    newclient.Close();
    MessageBox.Show(result);
  }
  else
  {
    MessageBox.Show("銜接辦事器掉敗", "友誼提醒");
  }
}

願望本文所述對年夜家的C#法式設計有所贊助。

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