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

namespace SocketTest
{
    public partial class Server : Form
    {
        Thread serverThread;
        Thread clientThread;
        TcpListener serverTcp;
        TcpClient clientTcp;

        public Server()
        {
            InitializeComponent();
        }

        private void ServerStart()
        {
            //创建IPEndPoint实例
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6001);
            /*
            //创建一个套接字
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //将所创建的套接字与IPEndPoint绑定
            serverSocket.Bind(ipep);
            //设置套接字为收听模式
            serverSocket.Listen(10);
            */
            serverTcp = new TcpListener(ipep);
            serverTcp.Start();

            while (true)
            {
                try
                {
                    //在套接字上接收接入的连接
                    //clientSocket = serverSocket.Accept();
                    clientTcp = serverTcp.AcceptTcpClient();
                    
                    clientThread = new Thread(new ThreadStart(ReceiveData));
                    clientThread.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("listening Error: " + ex.Message);
                }
            }
        }

        private void ReceiveData()
        {
            bool keepalive = true;
            TcpClient s = clientTcp;
            NetworkStream ns = s.GetStream();
            Byte[] buffer = new Byte[1024];

            //根据收听到的客户端套接字向客户端发送信息
            IPEndPoint clientep = (IPEndPoint)s.Client.RemoteEndPoint;
            lstServer.Items.Add("Client：" + clientep.Address + "("+clientep.Port+")");
            string welcome = "Welcome to my test sever ";
            byte[] data = new byte[1024];
            data = Encoding.ASCII.GetBytes(welcome);
            //s.Send(data, data.Length, SocketFlags.None);
            ns.Write(data,0, data.Length);

            while (keepalive)
            {
                //在套接字上接收客户端发送的信息
                int bufLen = 0;
                try
                {
                    bufLen = s.Available;
                    //s.Receive(buffer, 0, bufLen, SocketFlags.None);
                    ns.Read(buffer, 0, bufLen);
                    if (bufLen == 0)
                        continue;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Receive Error:" + ex.Message);
                    return;
                }
                clientep = (IPEndPoint)s.Client.RemoteEndPoint;
                string clientcommand = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, bufLen);

                lstServer.Items.Add(clientcommand + "("+clientep.Address + ":"+clientep.Port+")");

            }
            
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            serverThread = new Thread(new ThreadStart(ServerStart));
            serverThread.Start();
            lstServer.Items.Add("Server Start .....");
        }
    }
}