zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#中的Socket编程-TCP客户端

2023-09-11 14:16:45 时间

TCP客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TCP_client_communication
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //发起建立连接的请求
            //Parse:将一个字符串的ip地址转换成一个IPAddress对象
            IPAddress ipaddress = IPAddress.Parse("192.168.123.1");
            EndPoint point = new IPEndPoint(ipaddress, 7788);
            tcpClient.Connect(point);//通过IP和端口号来定位一个所要连接的服务器端

            byte[] data = new byte[1024];
            //传递一个byte数组,用于接收数据。length表示接收了多少字节的数据
            int length = tcpClient.Receive(data);

            string message = Encoding.UTF8.GetString(data, 0, length);//只将接收到的数据进行转化

            Console.WriteLine("Server:"+message);

            //向服务器端发送消息
            Console.Write("Client:");
            string message2 = Console.ReadLine();//读取用户的输入
            //将字符串转化为字节数组,然后发送到服务器端
            tcpClient.Send(Encoding.UTF8.GetBytes(message2));

            Console.ReadKey();

        }
    }
}