Socket-tcp协议客户端与服务器端互联

客户端

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

/// <summary>
/// 客户端
/// </summary>
namespace tcp协议客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个Socket
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //发起建立连接的请求
            IPAddress iPAddress = IPAddress.Parse("192.168.3.35");//可以字符串转换成ipaddress的对象
            EndPoint point = new IPEndPoint(iPAddress,7788);
            tcpClient.Connect(point);//通过ip和端口号定位一个服务器端

            //连接成功 接收消息
            byte[] data = new byte[1024];
            int length = tcpClient.Receive(data);//length表示接收了多少数据
            string message = Encoding.UTF8.GetString(data, 0, length);//只把接收到的数据转化
            Console.WriteLine(message);

            //--------向服务器端发送消息------------
            string message2 = Console.ReadLine();
            tcpClient.Send(Encoding.UTF8.GetBytes(message2));//把字符串转换为字节数组发送到服务器端
             

            Console.ReadKey();

        }
    }
}

服务器端

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

/// <summary>
/// 服务器端
/// </summary>
namespace tcp协议
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建Socket
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定ip和端口号 192.168.3.35
            IPAddress iPAddress = new IPAddress(new byte[] { 192,168,3,35 });//ipaddress是对ip和端口进行封装的类
            EndPoint point = new IPEndPoint(iPAddress,7788);// 向系统申请一个可用的ip端口号
            tcpServer.Bind(point);
            //开始监听(等待客户端链接)
            tcpServer.Listen(100);//最大连接数
            Console.WriteLine("开始监听");

            //接收 返回一个clientSocket
            Socket clientScocket= tcpServer.Accept();//暂停当前线程,直到一个客户端连接过来之后进行下面的操作
            Console.WriteLine("一个客户端连接过来");
            
            //向客户端发送一个返回消息
            string message = "hallo 你好";
            byte[] data= Encoding.UTF8.GetBytes(message);//对字符串做编码,等到一个字节数组
            clientScocket.Send(data);
            Console.WriteLine("向客户端发送了一条数据");

            //-----------------接收服务器端消息-------------------
            byte[] data2 = new byte[1024];//传建一个字节数组接收客户端发来的消息
            int length = clientScocket.Receive(data2);
            string message2 = Encoding.UTF8.GetString(data2, 0, length);//把字节数组转换为字符串
            Console.WriteLine("接收了一条消息" + message2);

            Console.ReadKey();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42459006/article/details/83418549