C# Socket之TCP客户端

2017-08-11  本文已影响0人  菜鸟程序猿
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);
                    }
                }
            }         
        }
    }
}
image.png
上一篇 下一篇

猜你喜欢

热点阅读