標籤: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(轉)