Socket编程 (毗连,发送消息) (Tcp、Udp) - Part1

火影  论坛元老 | 2024-9-10 09:07:49 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1026|帖子 1026|积分 3078

Socket编程 (毗连,发送消息) (Tcp、Udp)


本篇文章主要实现Socket在Tcp\Udp协议下相互通讯的方式。(服务器端与客户端的通讯)
1.基于Tcp协议的Socket通讯雷同于B/S架构,面向毗连,但差别的是服务器端可以向客户端主动推送消息。
利用Tcp协议通讯必要具备以下几个条件:
(1).创建一个套接字(Socket)
(2).绑定服务器端IP地址及端口号–服务器端
(3).利用Listen()方法开启监听–服务器端
(4).利用Accept()方法尝试与客户端创建一个毗连–服务器端
(5).利用Connect()方法与服务器创建毗连–客户端
(5).利用Send()方法向创建毗连的主机发送消息
(6).利用Recive()方法接受来自创建毗连的主机的消息(可靠毗连)

 2.基于Udp协议是无毗连模式通讯,占用资源少,相应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠毗连)
(1).创建一个套接字(Socket)
(2).绑定服务器端IP地址及端口号–服务器端
(3).通过SendTo()方法向指定主机发送消息(需提供主机IP地址及端口)
(4).通过ReciveFrom()方法吸收指定主机发送的消息(需提供主机IP地址及端口)
    

1、服务端

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

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

服务器端:

基于Udp协议下通讯结果如下图:
客户端:

服务器端:

总结

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

火影

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表