C# Socket网络通信_TCP(TcpListener和TcpClient)

简单Socket-Tcp通信

在本文中涉及到通信,仅做简单的通信(服务端接受消息,由客户端发出消息)
如有需要,根据需求可直接copy使用

1.关键字-TcpListener

需要引用命名空间:

using System.Net;
using System.Net.Sockets;

服务端代码:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Socket_TcpListener
{
    class Program
    {
        static void Main(string[] args)
        {
            SocketStart();          //开启socket通信
        }


        private static TcpListener tcpServer;

        /// <summary>
        /// 建立TCP连接
        /// </summary>
        private static void SocketStart()
        {
            int port = 11810;
            IPAddress ip = IPAddress.Parse("192.168.11.83");           //监听本地ip和端口号   
            IPEndPoint localIPEndPoint = new IPEndPoint(ip, port);

            tcpServer = new TcpListener(localIPEndPoint);
            tcpServer.Start();
            Console.WriteLine(ip+" 端口号: " + port + " 开启成功");

            TcpClient tempTcpClient = tcpServer.AcceptTcpClient();
            ReceiveMsg(tempTcpClient);

        }

        /// <summary>
        /// 接受来自客户端的消息
        /// </summary>
        /// <param name="tempTcpClient"></param>
        private static void ReceiveMsg(TcpClient tempTcpClient)
        {
            while (true)
            {
                try
                {
                    NetworkStream stream = tempTcpClient.GetStream();
                    byte[] data = new byte[120];         //用于接收数据的byte数组
                    stream.Read(data, 0, data.Length);   //读取

                    string receive = Encoding.GetEncoding("GBK").GetString(data);
                    Console.WriteLine(" 从客户端 " + tempTcpClient.Client.LocalEndPoint.ToString() + " 传来的消息: " + receive);
                }
                catch
                {
                    Console.WriteLine("与客户端 " + tempTcpClient.Client.LocalEndPoint.ToString() + " 连接中断");
                    tempTcpClient = tcpServer.AcceptTcpClient();
                }
            }
        }
    }
}

2.关键字-TcpClient

客户端代码:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Socket_TcpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            string content = "今天又是元气满满的一天";     //需要发送的消息内容
            byte[] data = Encoding.GetEncoding("GBK").GetBytes(content);    //转换为byte数组

            ClientSocketStart(data);        //开启socket通信
            Console.ReadKey();
        }


        /// <summary>
        /// Tcp客户端
        /// </summary>
        /// <param name="data"></param>
        public static void ClientSocketStart(byte[] data)
        {
            TcpClient tcpClient; 
            int localPort = 11821;
            IPAddress localIp = IPAddress.Parse("192.168.11.83");
            IPEndPoint localEndPoint = new IPEndPoint(localIp, localPort);      //需要连接的本地客户端ip和端口号

            int remotePort = 11810;
            IPAddress remoteIp = IPAddress.Parse("192.168.11.83");
            IPEndPoint remoteEndPoint = new IPEndPoint(remoteIp, remotePort);   //需要连接的远端服务端ip和端口号

            tcpClient = new TcpClient(localEndPoint);
            tcpClient.Connect(remoteEndPoint);
            NetworkStream stream = tcpClient.GetStream();

            try
            {
                stream.Write(data, 0, data.Length);
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " 向服务端发送消息成功 ");
            }
            catch
            {
                Console.WriteLine("连接中断");
            }
        }
    }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页