[C#]Socket简单TCP客户端-服务端
服务端
using System; using System.Net; using System.Net.Sockets; using System.Text; namespace TcpServer { internal class Program { static void Main(string[] args) { Socket theSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress theIPAddress = new IPAddress(new byte[] { 192,168,2,133 }); IPEndPoint theIPEndPoint = new IPEndPoint(theIPAddress, 7788); theSocket.Bind(theIPEndPoint); theSocket.Listen(100); Console.WriteLine("服务端已开启"); Socket theSocketServer = theSocket.Accept(); Console.WriteLine("客户端请求连接"); byte[] byt_aData = new byte[1024]; int intLength = theSocketServer.Receive(byt_aData); string strMessage = Encoding.UTF8.GetString(byt_aData, 0, intLength); Console.WriteLine("接收到了客户端的消息:" + strMessage); theSocketServer.Send(Encoding.UTF8.GetBytes("我是服务端")); theSocketServer.Close(); theSocket.Close(); } } }
客户端
using System.Net; using System.Net.Sockets; using System.Text; namespace TcpClient { class Program { static void Main(string[] args) { Socket theSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress theIPAddress = new(new byte[] { 192, 168, 2, 133 }); IPEndPoint theIPEndPoint = new(theIPAddress, 7788); theSocket.Connect(theIPEndPoint); Console.WriteLine("已连接服务端"); string strMessage = "我是客户端"; theSocket.Send(Encoding.UTF8.GetBytes(strMessage)); byte[] byt_aData = new byte[1024]; int intLength = theSocket.Receive(byt_aData); Console.WriteLine("收到服务端的消息:" + Encoding.UTF8.GetString(byt_aData, 0, intLength)); theSocket.Close(); } } }
演示(需要先开启服务端再开启客户端)
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!