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("连接中断");
            }
        }
    }
}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MelanceXin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值