网络编程学习笔记-Socket(TCP,UDP)

1.基于Tcp协议的Socket通讯类似于B/S架构,面向连接,但不同的是服务器端可以向客户端主动推送消息。

  使用Tcp协议通讯需要具备以下几个条件:

    (1).建立一个套接字(Socket)

    (2).绑定服务器端IP地址及端口号--服务器端

    (3).利用Listen()方法开启监听--服务器端

    (4).利用Accept()方法尝试与客户端建立一个连接--服务器端

    (5).利用Connect()方法与服务器建立连接--客户端

    (5).利用Send()方法向建立连接的主机发送消息

    (6).利用Recive()方法接受来自建立连接的主机的消息(可靠连接)

基于Udp协议是无连接模式通讯,占用资源少,响应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠连接)

    (1).建立一个套接字(Socket)

    (2).绑定服务器端IP地址及端口号--服务器端

    (3).通过SendTo()方法向指定主机发送消息(需提供主机IP地址及端口)

    (4).通过ReciveFrom()方法接收指定主机发送的消息(需提供主机IP地址及端口)

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 #region 命名空间
  7 using System.Net;
  8 using System.Net.Sockets;
  9 using System.Threading;
 10 #endregion
 11 namespace SocketServerConsole
 12 {
 13     class Program
 14     {
 15         static void Main(string[] args)
 16         {
 17             //主机IP
 18             IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("192.168.1.8"), 8686);
 19             Console.WriteLine("请选择连接方式:");
 20             Console.WriteLine("A.Tcp");
 21             Console.WriteLine("B.Udp");
 22             ConsoleKey key;
 23             while (true)
 24             {
 25                 key = Console.ReadKey(true).Key;
 26                 if (key == ConsoleKey.A) TcpServer(serverIP);
 27                 else if (key == ConsoleKey.B) UdpServer(serverIP);
 28                 else
 29                 {
 30                     Console.WriteLine("输入有误,请重新输入:");
 31                     continue;
 32                 }
 33                 break;
 34             }
 35         }
 36 
 37         #region Tcp连接方式
 38         /// <summary>
 39         /// Tcp连接方式
 40         /// </summary>
 41         /// <param name="serverIP"></param>
 42         public static void TcpServer(IPEndPoint serverIP)
 43         {
 44             Console.WriteLine("客户端Tcp连接模式");
 45             Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 46             tcpServer.Bind(serverIP);
 47             tcpServer.Listen(100);
 48             Console.WriteLine("开启监听...");
 49             new Thread(() =>
 50             {
 51                 while (true)
 52                 {
 53                     try
 54                     {
 55                         Socket tcpClient = tcpServer.Accept();
 56                        
 57                         byte[] data = new byte[1024];
 58                         try
 59                         {
 60                             int length = tcpClient.Receive(data);
 61                         }
 62                         catch (Exception ex)
 63                         {
 64                             Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
 65                             break;
 66                         }
 67                         Console.WriteLine(string.Format("收到消息:{0}", Encoding.UTF8.GetString(data)));
 68                         string sendMsg = "收到消息!";
 69                         tcpClient.Send(Encoding.UTF8.GetBytes(sendMsg));
 70                     }
 71                     catch (Exception ex)
 72                     {
 73                         Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
 74                         break;
 75                     }
 76                 }
 77             }).Start();
 78             Console.WriteLine("\n\n输入\"Q\"键退出。");
 79             ConsoleKey key;
 80             do
 81             {
 82                 key = Console.ReadKey(true).Key;
 83             } while (key != ConsoleKey.Q);
 84             tcpServer.Close();
 85         }
 86 
 87     
 88         #endregion
 89 
 90         #region Udp连接方式
 91         /// <summary>
 92         /// Udp连接方式
 93         /// </summary>
 94         /// <param name="serverIP"></param>
 95         public static void UdpServer(IPEndPoint serverIP)
 96         {
 97             Console.WriteLine("客户端Udp模式");
 98             Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 99             udpServer.Bind(serverIP);
100             IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
101             EndPoint Remote = (EndPoint)ipep;
102             new Thread(() =>
103             {
104                 while (true)
105                 {
106                     byte[] data = new byte[1024];
107                     try
108                     {
109                         int length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
110                     }
111                     catch (Exception ex)
112                     {
113                         Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
114                         break;
115                     }
116                     Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
117                     string sendMsg = "收到消息!";
118                     udpServer.SendTo(Encoding.UTF8.GetBytes(sendMsg), SocketFlags.None, Remote);
119                 }
120             }).Start();
121             Console.WriteLine("\n\n输入\"Q\"键退出。");
122             ConsoleKey key;
123             do
124             {
125                 key = Console.ReadKey(true).Key;
126             } while (key != ConsoleKey.Q);
127             udpServer.Close();
128         }
129         #endregion
130     }
131 }
View Code
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Text;
  5 using System.Threading.Tasks;
  6 #region 命名空间
  7 using System.Net.Sockets;
  8 using System.Net;
  9 using System.Threading;
 10 #endregion
 11 namespace SocketClientConsole
 12 {
 13     class Program
 14     {
 15         static void Main(string[] args)
 16         {//主机IP
 17             IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("192.168.1.8"), 8686);
 18             Console.WriteLine("请选择连接方式:");
 19             Console.WriteLine("A.Tcp");
 20             Console.WriteLine("B.Udp");
 21             ConsoleKey key;
 22             while (true)
 23             {
 24                 key = Console.ReadKey(true).Key;
 25                 if (key == ConsoleKey.A) TcpServer(serverIP);
 26                 else if (key == ConsoleKey.B) UdpClient(serverIP);
 27                 else
 28                 {
 29                     Console.WriteLine("输入有误,请重新输入:");
 30                     continue;
 31                 }
 32                 break;
 33             }
 34         }
 35 
 36         #region Tcp连接方式
 37         /// <summary>
 38         /// Tcp连接方式
 39         /// </summary>
 40         /// <param name="serverIP"></param>
 41         public static void TcpServer(IPEndPoint serverIP)
 42         {
 43             Console.WriteLine("客户端Tcp连接模式");
 44             Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 45             try
 46             {
 47                 tcpClient.Connect(serverIP);
 48             }
 49             catch (SocketException e)
 50             {
 51                 Console.WriteLine(string.Format("连接出错:{0}", e.Message));
 52                 Console.WriteLine("点击任何键退出!");
 53                 Console.ReadKey();
 54                 return;
 55             }
 56             Console.WriteLine("客户端:client-->server");
 57             string message = "我上线了...";
 58             tcpClient.Send(Encoding.UTF8.GetBytes(message));
 59             Console.WriteLine(string.Format("发送消息:{0}", message));
 60             new Thread(() =>
 61             {
 62                 while (true)
 63                 {
 64                     byte[] data = new byte[1024];
 65                     try
 66                     {
 67                         int length = tcpClient.Receive(data);
 68                     }
 69                     catch (Exception ex)
 70                     {
 71                         Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
 72                         break;
 73                     }
 74                     Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
 75                 }
 76             }).Start();
 77             Console.WriteLine("\n\n输入\"Q\"键退出。");
 78             ConsoleKey key;
 79             do
 80             {
 81                 key = Console.ReadKey(true).Key;
 82             } while (key != ConsoleKey.Q);
 83             tcpClient.Close();
 84         }
 85         #endregion
 86 
 87         #region Udp连接方式
 88         /// <summary>
 89         /// Udp连接方式
 90         /// </summary>
 91         /// <param name="serverIP"></param>
 92         public static void UdpClient(IPEndPoint serverIP)
 93         {
 94             Console.WriteLine("客户端Udp模式");
 95             Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 96             string message = "我上线了...";
 97             udpClient.SendTo(Encoding.UTF8.GetBytes(message), SocketFlags.None, serverIP);
 98             Console.WriteLine(string.Format("发送消息:{0}", message));
 99             IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
100             EndPoint Remote = (EndPoint)sender;
101             new Thread(() =>
102             {
103                 while (true)
104                 {
105                     byte[] data = new byte[1024];
106                     try
107                     {
108                         int length = udpClient.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
109                     }
110                     catch (Exception ex)
111                     {
112                         Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
113                         break;
114                     }
115                     Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
116                 }
117             }).Start();
118             Console.WriteLine("\n\n输入\"Q\"键退出。");
119             ConsoleKey key;
120             do
121             {
122                 key = Console.ReadKey(true).Key;
123             } while (key != ConsoleKey.Q);
124             udpClient.Close();
125         }
126         #endregion
127     }
128 }
View Code

Tcp协议下通讯效果如下图:

  客户端:

  

  服务器端:

  

基于Udp协议下通讯效果如下图:

  客户端:

  

  服务器端:

  

总结:Tcp协议相对通讯来说相对可靠,信息不易丢失,Tcp协议发送消息,发送失败时会重复发送消息等原因。所以对于要求通讯安全较高的程序来 说,选择Tcp协议的通讯相对合适。Upd协议通讯个人是比较推荐的,占用资源小,低延时,响应速度快。至于可靠性是可以通过一些应用层加以封装控制得到 相应的满足。

作者:曾庆雷
出处:http://www.cnblogs.com/zengqinglei
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明, 且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利

猜你喜欢

转载自www.cnblogs.com/anyihen/p/12977095.html