相关文章推荐
儒雅的书包  ·  郑东新区一日游旅游线路推荐 - 各区一日游推荐·  1 月前    · 
任性的冰淇淋  ·  财政部:今年四季度增加发行2023年国债1万 ...·  8 月前    · 
温柔的杨桃  ·  连续20年杀入季后赛有多难?NBA历史仅四队 ...·  10 月前    · 
帅气的登山鞋  ·  “萨姆规则”霸榜美国热搜! ...·  11 月前    · 
坏坏的饭盒  ·  黄山市徽州区:转移安置“555”工作机制为安 ...·  1 年前    · 
Code  ›  C# TCP通讯示例开发者社区
string tcp tcpclient
https://cloud.tencent.com/developer/article/1772833
强健的四季豆
2 年前
作者头像
zls365
0 篇文章

C# TCP通讯示例

前往专栏
腾讯云
开发者社区
文档 意见反馈 控制台
首页
学习
活动
专区
工具
TVP
文章/答案/技术大牛
发布
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
社区首页 > 专栏 > CSharp编程大全 > C# TCP通讯示例

C# TCP通讯示例

作者头像
zls365
发布 于 2021-01-13 16:07:01
1.5K 0
发布 于 2021-01-13 16:07:01
举报

示例目的:使用控制台项目模板分别新建一个 服务器 和一个客户端,实现两两通讯

1. 新建服务器项目

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace server
    class Program
        static TcpClient tcpClient;
        static NetworkStream stream;
        static void Main(string[] args)
                var serverIPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000); // 当前服务器使用的ip和端口
                TcpListener tcpListener = new TcpListener(serverIPEndPoint);
                tcpListener.Start();
                Console.WriteLine("服务端已启用......"); // 阻塞线程的执行,直到一个客户端连接
                tcpClient = tcpListener.AcceptTcpClient();
                Console.WriteLine("已连接.");
                stream = tcpClient.GetStream();          // 创建用于发送和接受数据的NetworkStream
                #region 开启线程保持通讯
                var t1 = new Thread(ReceiveMsg);
                t1.Start();
                var t2 = new Thread(SendMsg);
                t2.Start();
                #endregion
            catch (Exception ex)
                Console.WriteLine(ex.Message);
                Console.ReadKey();
        /// <summary>
        /// 发送消息
        /// </summary>
        static void SendMsg()
            string message = string.Empty;
            byte[] messageBytes;
                while (true)
                    message = Console.ReadLine().ToString();        // 获取控制台字符串
                    messageBytes = Encoding.UTF8.GetBytes(message); // 将消息编码成字符串数组
                    stream.Write(messageBytes, 0, messageBytes.Length);
            catch (Exception ex)
                Console.WriteLine(ex.Message);
                Console.ReadKey();
        /// <summary>
        /// 接收消息
        /// </summary>
        static void ReceiveMsg()
            byte[] buffer = new byte[1024]; // 预设最大接受1024个字节长度,可修改
            int count = 0;
                while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
                    Console.WriteLine($"{tcpClient.Client.LocalEndPoint.ToString()}:{Encoding.UTF8.GetString(buffer, 0, count)}");
            catch (Exception ex)
                Console.WriteLine(ex.Message);
                Console.ReadKey();

2. 新建客户端项目

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace client
    class Program
        static TcpClient tcpClient;
        static NetworkStream stream;
        static void Main(string[] args)
                var clientIPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4196); // 当前客户端使用的ip和端口
                tcpClient = new TcpClient(clientIPEndPoint);
                var serverIPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000); // 当前服务器使用的ip和端口
                tcpClient.Connect(serverIPEndPoint);    // 连接服务器
                var isConnected = tcpClient.Connected;
                Console.WriteLine("客户端已启用......");
                stream = tcpClient.GetStream();         // 创建用于发送和接受数据的NetworkStream
                #region 开启线程保持通讯
                var t1 = new Thread(ReceiveMsg);
                t1.Start();
                var t2 = new Thread(SendMsg);
                t2.Start();
                #endregion
            catch (Exception ex)
                Console.WriteLine(ex.Message);
                Console.ReadKey();
        /// <summary>
        /// 接收消息
        /// </summary>
        static void ReceiveMsg()
            byte[] buffer = new byte[1024]; // 预设最大接受1024个字节长度,可修改
            int count = 0;
                while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
                    Console.WriteLine($"{tcpClient.Client.LocalEndPoint.ToString()}:{Encoding.UTF8.GetString(buffer, 0, count)}");
            catch (Exception ex)
                Console.WriteLine(ex.Message);
                Console.ReadKey();
        /// <summary>
        /// 发送消息
        /// </summary>
        static void SendMsg()
            string message = string.Empty;
            byte[] messageBytes;
                while (true)
                    message = Console.ReadLine().ToString();        // 获取控制台字符串
                    messageBytes = Encoding.UTF8.GetBytes(message); // 将消息编码成字符串数组
                    stream.Write(messageBytes, 0, messageBytes.Length);
            catch (Exception ex)
                Console.WriteLine(ex.Message);
                Console.ReadKey();
 
推荐文章
儒雅的书包  ·  郑东新区一日游旅游线路推荐 - 各区一日游推荐
1 月前
任性的冰淇淋  ·  财政部:今年四季度增加发行2023年国债1万亿元 作为特别国债管理-新华网
8 月前
温柔的杨桃  ·  连续20年杀入季后赛有多难?NBA历史仅四队做到,湖凯均无缘|湖人|乔丹|马刺队|总冠军|76人队_网易订阅
10 月前
帅气的登山鞋  ·  “萨姆规则”霸榜美国热搜! 美国失业率增至4.3% “衰退交易”来势汹汹|美联储_新浪财经_新浪网
11 月前
坏坏的饭盒  ·  黄山市徽州区:转移安置“555”工作机制为安全度汛保驾护航_安徽省应急管理厅
1 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号