using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Client
{
    public partial class Client : Form
    {
        TcpClient clientTcp;
        Thread clientThread;
        NetworkStream ns;

        public Client()
        {
            InitializeComponent();
        }

        private void ConnectToServer()
        {
            byte[] data = new byte[1024];

            //创建一个套接字
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001);
            //clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientTcp = new TcpClient();

            //将套接字与远程服务器地址相连
            try
            {
                //clientSocket.Connect(ipep);
                clientTcp.Connect(ipep);
            }
            catch (SocketException ex)
            {
                MessageBox.Show("connect error: " + ex.Message);
                return;
            }

            ns = clientTcp.GetStream();
            while (true)
            {
                //接收服务器信息
                int bufLen = 0;
                try
                {
                    //bufLen = clientSocket.Available;
                    bufLen = clientTcp.Available;

                    //clientSocket.Receive(data, 0, bufLen, SocketFlags.None);
                    ns.Read(data, 0, bufLen);
                    if (bufLen == 0)
                    {
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Receive Error:" + ex.Message);
                    return;
                }

                string clientcommand = System.Text.Encoding.ASCII.GetString(data).Substring(0, bufLen);

                lstClient.Items.Add(clientcommand);

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            clientThread = new Thread(new ThreadStart(ConnectToServer));
            clientThread.Start();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            
            //向服务器发送信息
          
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(txtClient.Text);
            //clientSocket.Send(data, data.Length, SocketFlags.None);
            ns.Write(data, 0, data.Length);
        }
    }
}