首页 > 代码库 > C# Socket 入门1(转)

C# Socket 入门1(转)

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(转)