火影 发表于 2024-9-10 09:07:49

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

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()方法接受来自创建毗连的主机的消息(可靠毗连)
https://i-blog.csdnimg.cn/direct/47a6f560ec6b458cbb579ee9e2a1ef27.png
 2.基于Udp协议是无毗连模式通讯,占用资源少,相应速度快,延时低。至于可靠性,可通过应用层的控制来满足。(不可靠毗连)
(1).创建一个套接字(Socket)
(2).绑定服务器端IP地址及端口号–服务器端
(3).通过SendTo()方法向指定主机发送消息(需提供主机IP地址及端口)
(4).通过ReciveFrom()方法吸收指定主机发送的消息(需提供主机IP地址及端口)
    https://i-blog.csdnimg.cn/direct/e3077e7d742e44daafbf77d50a7b19cb.png
1、服务端

using System;
using System.Collections.Generic;
using System.Text;
#region 命名空间
using System.Net;
using System.Net.Sockets;
using System.Threading;
#endregion

namespace SocketServerConsole
{
    class Program
    {
      #region 控制台主函数
      /// <summary>
      /// 控制台主函数
      /// </summary>
      /// <param name="args"></param>
      static void Main(string[] args)
      {
            //主机IP
            IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("192.168.1.105"), 8686);
            Console.WriteLine("请选择连接方式:");
            Console.WriteLine("A.Tcp");
            Console.WriteLine("B.Udp");
            ConsoleKey key;
            while (true)
            {
                key = Console.ReadKey(true).Key;
                if (key == ConsoleKey.A) TcpServer(serverIP);
                else if (key == ConsoleKey.B) UdpServer(serverIP);
                else
                {
                  Console.WriteLine("输入有误,请重新输入:");
                  continue;
                }
                break;
            }
      }
      #endregion

      #region Tcp连接方式
      /// <summary>
      /// Tcp连接方式
      /// </summary>
      /// <param name="serverIP"></param>
      public static void TcpServer(IPEndPoint serverIP)
      {
            Console.WriteLine("客户端Tcp连接模式");
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            tcpServer.Bind(serverIP);
            tcpServer.Listen(100);
            Console.WriteLine("开启监听...");
            new Thread(() =>
            {
                while (true)
                {
                  try
                  {
                        TcpRecive(tcpServer.Accept());
                  }
                  catch (Exception ex)
                  {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                  }
                }
            }).Start();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            tcpServer.Close();
      }

      public static void TcpRecive(Socket tcpClient)
      {
            new Thread(() =>
            {
                while (true)
                {
                  byte[] data = new byte;
                  try
                  {
                        int length = tcpClient.Receive(data);
                  }
                  catch (Exception ex)
                  {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                  }
                  Console.WriteLine(string.Format("收到消息:{0}", Encoding.UTF8.GetString(data)));
                  string sendMsg = "收到消息!";
                  tcpClient.Send(Encoding.UTF8.GetBytes(sendMsg));
                }
            }).Start();
      }
      #endregion

      #region Udp连接方式
      /// <summary>
      /// Udp连接方式
      /// </summary>
      /// <param name="serverIP"></param>
      public static void UdpServer(IPEndPoint serverIP)
      {
            Console.WriteLine("客户端Udp模式");
            Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(serverIP);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)ipep;
            new Thread(() =>
            {
                while (true)
                {
                  byte[] data = new byte;
                  try
                  {
                        int length = udpServer.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
                  }
                  catch (Exception ex)
                  {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                  }
                  Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                  string sendMsg = "收到消息!";
                  udpServer.SendTo(Encoding.UTF8.GetBytes(sendMsg), SocketFlags.None, Remote);
                }
            }).Start();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            udpServer.Close();
      }
      #endregion
    }
}
2、客户端

using System;
using System.Collections.Generic;
using System.Text;
#region 命名空间
using System.Net.Sockets;
using System.Net;
using System.Threading;
#endregion

namespace SocketClientConsole
{
    class Program
    {
      #region 控制台主函数
      /// <summary>
      /// 控制台主函数
      /// </summary>
      /// <param name="args"></param>
      static void Main(string[] args)
      {
            //主机IP
            IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("192.168.1.77"), 8686);
            Console.WriteLine("请选择连接方式:");
            Console.WriteLine("A.Tcp");
            Console.WriteLine("B.Udp");
            ConsoleKey key;
            while (true)
            {
                key = Console.ReadKey(true).Key;
                if (key == ConsoleKey.A) TcpServer(serverIP);
                else if (key == ConsoleKey.B) UdpClient(serverIP);
                else
                {
                  Console.WriteLine("输入有误,请重新输入:");
                  continue;
                }
                break;
            }
      }
      #endregion

      #region Tcp连接方式
      /// <summary>
      /// Tcp连接方式
      /// </summary>
      /// <param name="serverIP"></param>
      public static void TcpServer(IPEndPoint serverIP)
      {
            Console.WriteLine("客户端Tcp连接模式");
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                tcpClient.Connect(serverIP);
            }
            catch (SocketException e)
            {
                Console.WriteLine(string.Format("连接出错:{0}", e.Message));
                Console.WriteLine("点击任何键退出!");
                Console.ReadKey();
                return;
            }
            Console.WriteLine("客户端:client-->server");
            string message = "我上线了...";
            tcpClient.Send(Encoding.UTF8.GetBytes(message));
            Console.WriteLine(string.Format("发送消息:{0}", message));
            new Thread(() =>
            {
                while (true)
                {
                  byte[] data = new byte;
                  try
                  {
                        int length = tcpClient.Receive(data);
                  }
                  catch (Exception ex)
                  {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                  }
                  Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                }
            }).Start();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            tcpClient.Close();
      }
      #endregion

      #region Udp连接方式
      /// <summary>
      /// Udp连接方式
      /// </summary>
      /// <param name="serverIP"></param>
      public static void UdpClient(IPEndPoint serverIP)
      {
            Console.WriteLine("客户端Udp模式");
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            string message = "我上线了...";
            udpClient.SendTo(Encoding.UTF8.GetBytes(message), SocketFlags.None, serverIP);
            Console.WriteLine(string.Format("发送消息:{0}", message));
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;
            new Thread(() =>
            {
                while (true)
                {
                  byte[] data = new byte;
                  try
                  {
                        int length = udpClient.ReceiveFrom(data, ref Remote);//接受来自服务器的数据
                  }
                  catch (Exception ex)
                  {
                        Console.WriteLine(string.Format("出现异常:{0}", ex.Message));
                        break;
                  }
                  Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                }
            }).Start();
            Console.WriteLine("\n\n输入\"Q\"键退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            udpClient.Close();
      }
      #endregion
    }
}
Tcp协议下通讯结果如下图:
客户端:
  https://i-blog.csdnimg.cn/direct/577a585a5c004247ae0c807da6ec6dc9.png
服务器端:
https://i-blog.csdnimg.cn/direct/2973aba6818b4a2cbe7591899c73bedc.png
基于Udp协议下通讯结果如下图:
客户端:https://i-blog.csdnimg.cn/direct/7c59f18e81e14181ab70970e4e125988.png
服务器端:
https://i-blog.csdnimg.cn/direct/78d37b601b6d4d4d83cc66729d205cc9.png
总结

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Socket编程 (毗连,发送消息) (Tcp、Udp) - Part1