using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketClient
{
    internal class Program
    {
        private static Socket Client;
        static void Main(string[] args)
        {
            Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Client.Connect("127.0.0.1", 12345);
            Console.WriteLine("已连接，注册名字");
            string name = Console.ReadLine();
            Client.Send(Encoding.UTF8.GetBytes(name));

            //接受服务端信息-多线程
            Thread th = new Thread(ReceiveMsg);
            th.Start();
            while (true)
            {
                string msg = Console.ReadLine();
                Client.Send(Encoding.UTF8.GetBytes(msg));
            }
        }
        static void ReceiveMsg()
        {
            byte[] buffer = new byte[1024];
            try
            {
                while(true)
                {

                    int num = Client.Receive(buffer);
                    if(num == 0) break;//服务端关闭
                    string message = Encoding.UTF8.GetString(buffer, 0, num);
                    Console.WriteLine(message);
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
            finally
            {
                Client.Close();
                Console.WriteLine("服务端关闭");
            }
            
            

        }
    }
}
