[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();
        }
    }
}
复制代码

演示(需要先开启服务端再开启客户端)

 

posted @   SairenjiHaruna  阅读(281)  评论(0编辑  收藏  举报
编辑推荐:
· 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 重磅开源!
点击右上角即可分享
微信分享提示