C# Socket伺服器用戶端執行個體 串連原型

來源:互聯網
上載者:User

伺服器端程式

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace SocketServer
{
 /// <summary>
 /// Class1 的摘要說明。
 /// </summary>
 class Class1
 {
  /// <summary>
  /// 應用程式的主進入點。
  /// </summary>
  //定義連接埠號碼
  private const int porNum=81;
  [STAThread]
  static void Main(string[] args)
  {
   //
   // TODO: 在此處添加代碼以啟動應用程式
   //
   bool done=false;
   TcpListener listener=new TcpListener(porNum);
   listener.Start();
   while(!done){
   Console.Write("正在偵聽81連接埠...");
    TcpClient client=listener.AcceptTcpClient();
    Console.WriteLine("\n處理串連請求...");
    NetworkStream ns=client.GetStream();
    //ns.Read(,0,);
    byte[] bytes=new byte[1024];
    int bytesRead=ns.Read(bytes,0,bytes.Length);
    Console.WriteLine(Encoding.BigEndianUnicode.GetString(bytes,0,bytesRead));
    byte[] byteTime=Encoding.ASCII.GetBytes(DateTime.Now.ToString());
    try
    {
     ns.Write(byteTime,0,byteTime.Length);
     ns.Close();
     client.Close();
    }
    catch(Exception ex){
    Console.WriteLine(ex.ToString());
    }
   }
   listener.Stop();
  }
 }
}

Web用戶端

添加命名空間:
using System.Net;
using System.Net.Sockets;
using System.Text;

串連代碼:
private void socketButton_Click(object sender, System.EventArgs e)
  {//串連伺服器程式
   try
   {
    //開始串連
    TcpClient client=new TcpClient("192.168.0.100",81);
    NetworkStream ns=client.GetStream();
    byte[] byteTime=Encoding.BigEndianUnicode.GetBytes("用戶端資料提交\n");
    ns.Write(byteTime,0,byteTime.Length);
    //返回用戶端資訊
    byte[] clientIp=Encoding.BigEndianUnicode.GetBytes("用戶端IP地址:"+Request.UserHostAddress+"\n");
    ns.Write(clientIp,0,clientIp.Length);
    byte[] bytes=new byte[1024];
    int bytesRead=ns.Read(bytes,0,bytes.Length);
    showLabel.Text="伺服器返回資訊"+Encoding.ASCII.GetString(bytes,0,bytesRead);
    client.Close();
   }
   catch(Exception ex)
   {
    showLabel.Text="拋出異常"+ex.ToString();
   }
   finally{}
  }

聯繫我們

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