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地址及端口)

    

    

上代码:由于个人代码风格,习惯性将两种方式写在一起,让用户主动选择Tcp\Udp协议通讯

服务器端:   

using System;using System.Collections.Generic;using System.Text;#region 命名空间using System.Net;using System.Net.Sockets;using System.Threading;#endregionnamespace 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[1024];                    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[1024];                    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    }}

客户端:

  

using System;using System.Collections.Generic;using System.Text;#region 命名空间using System.Net.Sockets;using System.Net;using System.Threading;#endregionnamespace 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[1024];                    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[1024];                    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协议下通讯效果如下图:

  客户端:

  

  服务器端:

  

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

  客户端:

  

  服务器端:

  

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

附上源码:Socket-Part1.zip

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

相关推荐

  • 利用Tcp和socket实现的客户端与服务端的简单通信

    /*服务端*/ using System; using System.Collections.Generic; using System.Collections; using System.Colle ...

  • c#Socket通信实例

    在上一篇文章中介绍了Socket基础-TCP与UDP协议和他们之间的区别,这篇文章参考另一位前辈的博文重点记录下Socket的原理及两种协议的开发过程. 一.Socket通信简介 1.按惯例先来介绍下 ...

  • TCP、HTTP、Socket,傻傻分不清?

    作者:rebareba 地址:https://segmentfault.com/a/1190000014044351 前言 作为一名开发人员我们经常会听到HTTP协议.TCP/IP协议.UDP协议.S ...

  • C#socket编程

    我们做网络通信的时候需要有通信协议,在进行socket编程的时候有两种通信协议TCP.UDP,这次我们就用简单的方式在一台电脑建立TCP协议的服务器端和客户端并使之进行通信. 服务器端和客户端进行连接 ...

  • 川崎机器人-以太网连接的TCP/IP通信功能(TCP/UDP通讯命令)······

    川崎机器人-以太网连接的TCP/IP通信功能(TCP/UDP通讯命令)&#183;&#183;&#183;&#183;&#183;&#183;

  • php socket通信(tcp/udp)

    注意 1.在socket_bind的时候ip地址不能真回环地址如127.0.0.1 2.server.php后台跑起来的时候 nohup php server.php > /var/tmp/a. ...

  • Windows Socket和Linux Socket编程的区别

    SOCKET在原理上应该是一样的,只是不同系统的运行机置有些不同.Socket 编程 windows到Linux代码移植遇到的问题1.一些常用函数的移植http://www.vckbase.com/d ...

  • 微信定时发送消息怎么弄

    现在微信有推出新功能定时发送消息功能,微信定时发送功能在哪里,该功能会给用户带来哪些便利呢,今日为你们带来的文章是关于微信定时发送消息功能介绍,还有不清楚小伙伴和小编一起去学习一下吧. 当前虽然有一些 ...

  • 微信新功能曝光,可以定时发送消息了!

    适用平台:安卓.ios 文字版教程: 1.首先看下这个专利,如图:它可以解决会话消息发送的效率低下的问题,能自动推荐发送时间,并按照推荐时间发送会话消息,有效提高会话消息的发送效率. 2.定时发送实现 ...

  • 微信8.0.7更新!可以定时发送消息了,还有这5个新功能

    2.分付功能上线 3.文件格式转换 在微信收到文档时,需要转换文件的格式,不用跳转App,打开「迅捷PDF转换器」小程序,可以直接从微信上选择文件,多种格式随意转换,历史文件还能保存在文件库. 4.视 ...

  • 面试中关于TCP UDP HTTP HTTPS的问题

    大家面试中问到这个问题该怎么答. 首先我把概念和之间的关系给大家简单的说下: http:是用于www浏览的一个协议. tcp:是机器之间建立连接用到的一个协议 1.TCP/IP 是个协议组,可分为三个 ...

  • Socket编程基础学习

    Socket编程基础学习

  • java实现向邮件发送消息

    发送邮件的方法 /** * 发送邮件 * @param user 发件人邮箱 * @param password 授权码(注意不是邮箱登录密码) * @param host * @param from ...