欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#Tcp服务端与客户端接收消息与发送消息

程序员文章站 2024-03-22 22:13:34
...

服务端的搭建

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace TCP服务器
{
    class Program
    {
        static void Main(string[] args)
        {
            //第一步创建socket对象 服务端
            Socket serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            //第二步绑定ip和端口号
            //这是自身电脑的ip,Parse可以直接转换为IPAddress的对象出去
            IPAddress ipAddress = IPAddress.Parse("192.168.1.105");
            //92代表端口号
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 92);
            //绑定
            serverSocket.Bind(ipEndPoint);
            //开始监听端口号
            serverSocket.Listen(0);

            //创建客户端
            Socket clientSocket = serverSocket.Accept();//接受一个客户端连接

            //选客户端发送一条消息
            string msg = "Hello client! 你好.....";
            //System.Text.Encoding.UTF8.GetBytes将一个字符串转为byte的序列
            byte[] data = System.Text.Encoding.UTF8.GetBytes(msg);
            clientSocket.Send(data);

            //接受客户端的一条消息
            byte[] dataBuffer = new byte[1024];//用来接受数据
            //接收到的消息将存入dataBuffer中,返回接收到了多少个数据
            int count = clientSocket.Receive(dataBuffer);
            //0到count个数据的内容
            string msgReceive = System.Text.Encoding.UTF8.GetString(dataBuffer,0,count);
            Console.WriteLine(msgReceive);

            //在客户端反馈消息后,暂停下
            Console.ReadKey();
            //先关闭客户端,在关闭服务端
            clientSocket.Close();
            serverSocket.Close();
        }
    }
}

客户端的搭建

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace TCP客户端
{
    class Program
    {
        static void Main(string[] args)
        {

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //服务端链接ip与端口号
            clientSocket.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.105"), 92));

            byte[] data = new byte[1024];
            int count = clientSocket.Receive(data);
            string msg = Encoding.UTF8.GetString(data, 0, count);
            Console.Write(msg);


            string s = Console.ReadLine();
            Console.Write(s);
            clientSocket.Send(Encoding.UTF8.GetBytes(s));

            Console.ReadKey();
            clientSocket.Close();
        }
    }
}