Socket 編程——一個簡單的例子

來源:互聯網
上載者:User

 

socket編程的一個簡單一實例

伺服器端C#代碼:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication3
{
    class ProgramServer
    {
       static void Main(string[] args)
       {
           while (true)     //持續監聽。
           {
               int port = 2000;
               string host = "172.16.4.11";//172.16.4.11要替換為你的IP。

               /**/
               ///建立終結點(EndPoint)
               IPAddress ip = IPAddress.Parse(host);//把ip地址字串轉換為IPAddress類型的執行個體
               IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的連接埠和ip初始化IPEndPoint類的新執行個體

               /**/
               ///建立socket並開始監聽
               Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立一個socket對像,如果用udp協議,則要用SocketType.Dgram類型的通訊端
               s.Bind(ipe);//綁定EndPoint對像(2000連接埠和ip地址)
               s.Listen(0);//開始監聽
               Console.WriteLine("等待用戶端串連......");

               /**/
               ///接受到client串連,為此串連建立新的socket,並接受資訊
               Socket temp = s.Accept();//為建立串連建立新的socket
               Console.WriteLine("建立串連");
               string recvStr = "";
               byte[] recvBytes = new byte[1024];
               int bytes;
               bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//從用戶端接受資訊
               recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
               Console.WriteLine("Server Get Message:{0}", recvStr);//把用戶端傳來的資訊顯示出來

               /**/
               ///給client端返回資訊
               string sendStr = Console.ReadLine(); //輸入任意語句,返回給用戶端。
               byte[] bs = Encoding.ASCII.GetBytes(sendStr);
               temp.Send(bs, bs.Length, 0);//返回資訊給用戶端
               temp.Close();
               s.Close();//關閉socket。
           }

        }
    }
}

 

用戶端C#代碼:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace socket2
{
    class ProgramClient
    {
        static void Main(string[] args)
        {
            try
            {
                while (true)
                {
                    int port = 2000;
                    string host = "172.16.4.11";//172.16.4.11要替換為你的IP。
                    /**/
                    IPAddress ip = IPAddress.Parse(host);
                    IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和連接埠轉化為IPEndpoint執行個體

                    /**/
                    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立Socket
                    Console.WriteLine("Conneting...");
                    sock.Connect(ipe);//串連到伺服器

                    /**/
                    ///向伺服器發送資訊
                    //string sendStr = "this is my first socket program";
                    string sendStr = Console.ReadLine();//輸入任意資訊,發送到伺服器端。
                    byte[] bs = Encoding.ASCII.GetBytes(sendStr);//把字串編碼為位元組
                    Console.WriteLine("Send Message");
                    sock.Send(bs, bs.Length, 0);//發送資訊

                    /**/
                    ///接受從伺服器返回的資訊
                    string recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes;
                    bytes = sock.Receive(recvBytes, recvBytes.Length, 0);//從伺服器端接受返回資訊
                    recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                    Console.WriteLine("Client Get Message:{0}", recvStr);//顯示伺服器返回資訊
                    /**/
                    ///一定記著用完socket後要關閉
                    sock.Close();
                }
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine("argumentNullException: {0}", e);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException:{0}", e);
            }
            Console.WriteLine("Press Enter to 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.