美文网首页
C# Socket之TCP客户端

C# Socket之TCP客户端

作者: 菜鸟程序猿 | 来源:发表于2017-08-11 17:38 被阅读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

相关文章

网友评论

      本文标题:C# Socket之TCP客户端

      本文链接:https://www.haomeiwen.com/subject/jjjrrxtx.html