C# Socket之TCP客户端

namespace TcpClient
{
    class Program
    {
        private static Thread  t;
        private static Socket clientScoket;
        private static byte[] data= new byte[1024];
        static void Main(string[] args)
        {
            ConnectToServer();//创建scoket对象并连接到服务器
           
            while (true)
            {
                string message2 = Console.ReadLine();
                SendMessage(message2);
            }
           
            Console.ReadKey();
        }
        static void ConnectToServer()
        {
            clientScoket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             clientScoket.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.145"), 8090));
            Console.WriteLine("已连接到服务器");
            t = new Thread(ReceiveMessage);//开启线程执行循环接收消息
            t.Start();

        }
        static void SendMessage(string message)//发送消息
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            clientScoket.Send(data);
        }
        static void ReceiveMessage()//接收消息
        {
            int length = 0;
            while (true)
            {
                if (clientScoket.Connected==true)
                {
                    length = clientScoket.Receive(data);
                    if (length != 0)
                    {
                        string message = Encoding.UTF8.GetString(data, 0, length);
                         Console.WriteLine(message);
                    }
                }
            }         
        }
    }
}
C# Socket之TCP客户端_第1张图片
image.png

你可能感兴趣的:(C# Socket之TCP客户端)