• c#写个基础的Socket通讯


    c#写个基础的Socket通讯

     晚上想写点东西,想想把我刚来公司学的Sockt通讯写上来吧。要写的简单易懂点,新人们可以借鉴下哦,用控制台写。

      先得说说Socket,与TCP/UDP啥关系,一直讲什么Socket通讯,TCP通讯,都被搞乱了,开始也搞不懂啥意思,引用网上大多数人讲的概念吧“Socket接口是TCP/IP网络的API,Socket接口定义了许多函数或例程,程序员可以用它们来开发TCP/IP网络上的应用程序。要学Internet上的TCP/IP网络编程,必须理解Socket接口。”我理解就是SOCKET是TCP、UDP的实现方式,用SOCKET编程可以实现TCP、UDP的通信。再通俗点,把Socket看成管子嘛,管子里传输液体或是固体,就是不同的协议嘛。

      好,下面切入主题看代码,代码不长,应该好懂。

    服务器端:

    复制代码
            static void Main(string[] args)
            {           
                int recv;//用于表示客户端发送的信息长度
                byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
                IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);//本机预使用的IP和端口
                Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                newsock.Bind(ipep);//绑定
                newsock.Listen(10);//监听
                Console.WriteLine("waiting for a client");
                Socket client = newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
                IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
                Console.WriteLine("connect with client:" + clientip.Address + " at port:" + clientip.Port);
                string welcome = "welcome here!";
                data = Encoding.ASCII.GetBytes(welcome);
                client.Send(data, data.Length, SocketFlags.None);//发送信息
                try
                {
                    while (true)
                    {//用死循环来不断的从客户端获取信息
                        data = new byte[1024];
                        recv = client.Receive(data);
                        Console.WriteLine("recv=" + recv);
                        if (recv == 0)//当信息长度为0,说明客户端连接断开
                            break;
                        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
                        client.Send(data, recv, SocketFlags.None);//发送信息
                    }
                }
                catch
                {
                    Console.WriteLine("Disconnected from" + clientip.Address);
                }
                client.Close();
                newsock.Close();           
            }
    复制代码

    客户端:

    复制代码
            static void Main(string[] args)
            {
                byte[] data = new byte[1024];
                Socket newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Console.Write("please input the server ip:");
                string ipadd = Console.ReadLine();
                Console.WriteLine();
                Console.Write("please input the server port:");
                int port = Convert.ToInt32(Console.ReadLine());
                IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);//服务器的IP和端口
                try
                {
                    //因为客户端只是用来向特定的服务器发送信息,所以不需要绑定本机的IP和端口。不需要监听。
                    newclient.Connect(ie);
                }
                catch (SocketException e)
                {
                    Console.WriteLine("unable to connect to server");
                    Console.WriteLine(e.ToString());
                    return;
                }
    
                newclient.Send(Encoding.Default.GetBytes("watchdog"));
                int recv = newclient.Receive(data);
                string stringdata = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine(stringdata);
                while (true)
                {
                    string input = Console.ReadLine();
                    if (input == "exit")
                        break;
                    newclient.Send(Encoding.ASCII.GetBytes(input));
                    data = new byte[1024];
                    recv = newclient.Receive(data);
                    stringdata = Encoding.ASCII.GetString(data, 0, recv);
                    Console.WriteLine(stringdata);
                }
                Console.WriteLine("disconnect from sercer");
                newclient.Shutdown(SocketShutdown.Both);
                newclient.Close();
            }
    复制代码

    客户端运行图

      先运行服务员,再运行客户端即可。好了这个程序麻雀虽小五脏俱全,还是很容易学习滴。延时下去还可以做个简易聊天室。

     
     
    分类: c#基础
  • 相关阅读:
    最新 蓝鲸人java校招面经 (含整理过的面试题大全)
    最新 上海轻轻java校招面经 (含整理过的面试题大全)
    最新 苏州朗动java校招面经 (含整理过的面试题大全)
    最新 医渡云java校招面经 (含整理过的面试题大全)
    变量的自动类型转换和强制类型转换(day01_10)
    java的数据类型(day01_09)
    常用的dos命令操作(day01_03)
    1.镜像-虚拟光驱-光驱
    Spring基于配置文件的方式来配置AOP
    Spring-AOP(切面的优先级&&&重用切点表达式)
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3373664.html
Copyright © 2020-2023  润新知