不断积累,必然飞跃,突破随之!

相信自己,开拓生活!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Socket编辑基础tcp通信

Posted on 2008-10-16 10:13  Tangyuan2017  阅读(212)  评论(0编辑  收藏  举报

 

SocketServer 端应用程序

static void Main(string[] args)
        {

            IPAddress address = IPAddress.Parse("127.0.0.1");
            IPEndPoint point = new IPEndPoint(address, 3000);
          
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(point);
            server.Listen(3);
            Socket client;
            byte[] buffer = new byte[1024];
            int i = 0;
            string data;
            Console.WriteLine("等待连接...");
            if ((client = server.Accept()) != null)//进程等待
            {
                Console.WriteLine("用户已连接...");
                while (true)
                {
                    if ((i = client.Receive(buffer)) != 0)//进程等待
                    {
                        data = System.Text.Encoding.UTF8.GetString(buffer, 0, i);
                        Console.WriteLine("收到的信息为{0}", data);
                        Console.Write("请输入回复信息:");
                        string input = Console.ReadLine();
                        client.Send(System.Text.Encoding.UTF8.GetBytes(input));
                    }
                }
            }

            Console.ReadLine();
        }

//*************************8888

socketClient客户端程序

  static void Main(string[] args)
        {
            IPAddress address = IPAddress.Parse("127.0.0.1");
          
            IPEndPoint point = new IPEndPoint(address, 3000);
            Socket Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Client.Connect(point);//进程等待
            Console.WriteLine("已连接到服务器...");
            byte[] buffer = new byte[1024];
            string data = null;
            while (true)
            {
                Console.Write("请输入要发送的信息:");
                string input;
                input = Console.ReadLine();
                if (input == "exit")
                    break;
                Client.Send(System.Text.Encoding.UTF8.GetBytes(input));
              
                int i = 0;
                i = Client.Receive(buffer);//进程等待
                if (i > 0)
                {
                    Console.Write("服务器回复信息:");
                    data = System.Text.Encoding.UTF8.GetString(buffer, 0, i);
                    Console.WriteLine(data);
                }
            }
            Console.WriteLine("断开连接...");
            Client.Shutdown(SocketShutdown.Both);
            Client.Close();
        }