C# Socket 入門1(轉)

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   os   ar   sp   資料   

1.   服務端程式

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.Net.Sockets;
 5 using System.Net;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             // 1.建立套節字
14             Socket sListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
15 
16             // 2.填充IP
17             IPAddress ip = IPAddress.Parse("127.0.0.1");
18             IPEndPoint ipe = new IPEndPoint(ip, 4321);
19 
20             // 3.綁定
21             sListen.Bind(ipe);
22 
23             // 4.監聽
24             sListen.Listen(2);
25 
26             // 5.迴圈接受客戶的串連請求
27             while (true)
28             {
29                 Socket clientSocket;
30                 try
31                 {
32                     clientSocket = sListen.Accept();
33                 }
34                 catch
35                 {
36                     throw;
37                 }
38                 // 向用戶端發送資料
39                 clientSocket.Send(Encoding.Unicode.GetBytes("你好呀!!!!"));
40             }
41         }
42 
43     }
44 }
45 

好完成,,服務端, 

2 現在請看用戶端

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 using System.Net.Sockets;
 5 using System.Net;
 6 
 7 namespace ConsoleApplication2
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             // 1.建立套節字
14             Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
15 
16             // 2.填寫遠程IP
17             IPAddress ip = IPAddress.Parse("127.0.0.1");
18             IPEndPoint ipe = new IPEndPoint(ip, 4321);
19 
20             // 3.串連伺服器21             Console.WriteLine("開始串連伺服器....");
22             s.Connect(ipe);
23 
24             // 4.接收資料
25             byte[] buffer = new byte[1024];
26             s.Receive(buffer, buffer.Length, SocketFlags.None);
27             var msg = Encoding.Unicode.GetString(buffer);
28             Console.WriteLine("接收訊息: {0}", msg);
29 
30             Console.ReadKey();
31         }
32     }
33 }

好了, 看看效果 ~~

簡單嗎 ~~   

C# Socket 入門1(轉)

聯繫我們

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