socket 서버 브라우저와 서버 클라이언트 실례

12131 단어 socket
1. 서버 및 브라우저
//본 컴퓨터의 loopback 네트워크 주소, 즉 127.0.0.1 IPADdress address = IPADdress.Loopback;            IPEndPoint endPoint = new IPEndPoint(address, 49152);            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            socket.Bind(endPoint);            socket.Listen(10);            Console.WriteLine("감청 시작, 포트 번호; {0}.",endPoint.Port);            while (true)            {                Socket client = socket.Accept();                Console.WriteLine(client.RemoteEndPoint);                byte[] buffer = new byte[4096];                int length = client.Receive(buffer, 4096, SocketFlags.None);                System.Text.Encoding utf8 = System.Text.Encoding.UTF8;                string requestString = utf8.GetString(buffer, 0, length);                Console.WriteLine(requestString);                string statusLine = "HTTP/1.1 200 OK\r";                byte[] statusLineBytes = utf8.GetBytes(statusLine);                string responseBody = "From Socket ServerHello,world.";                byte[] responseBodyBytes = utf8.GetBytes(responseBody);//응답하는 머리string responseHeader =string.Format("Content-Type:text/html;charset=UTF-8\rContent-Length:{0}\r",                    responseBody.Length);                byte[] responseHeaderBytes = utf8.GetBytes(responseHeader);//클라이언트에게 상태 메시지 클라이언트를 보냅니다.Send(statusLineBytes);//클라이언트에게 응답 헤더 클라이언트를 보냅니다.Send(responseHeaderBytes);                client.Send(new byte[] { 13, 10 });                client.Send(responseBodyBytes);                client.Close();                if (Console.KeyAvailable)                {                    break;                }                socket.Close();            }
 
마지막으로 브라우저 주소 표시줄에:http://localhost:49152
 
2. 서버 클라이언트
서버:
class Program

    {

        private static byte[] result = new byte[1024];

        private static int myProt = 8885;   // 

        static Socket serverSocket;

        static void Main(string[] args)

        {

            // IP 

            IPAddress ip = IPAddress.Parse("127.0.0.1");

            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            serverSocket.Bind(new IPEndPoint(ip, myProt));  // IP : 

            serverSocket.Listen(10);    // 10 

            Console.WriteLine(" {0} ", serverSocket.LocalEndPoint.ToString());

            // Clientsoket 

            Thread myThread = new Thread(ListenClientConnect);

            myThread.Start();

            Console.ReadLine();

        }



        /// <summary>

        ///  

        /// </summary>

        private static void ListenClientConnect()

        {

            while (true)

            {

                Socket clientSocket = serverSocket.Accept();

                clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));

                Thread receiveThread = new Thread(ReceiveMessage);

                receiveThread.Start(clientSocket);

            }

        }



        /// <summary>

        ///  

        /// </summary>

        /// <param name="clientSocket"></param>

        private static void ReceiveMessage(object clientSocket)

        {

            Socket myClientSocket = (Socket)clientSocket;

            while (true)

            {

                try

                {

                    // clientSocket 

                    int receiveNumber = myClientSocket.Receive(result);

                    Console.WriteLine(" {0} {1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));

                }

                catch(Exception ex)

                {

                    Console.WriteLine(ex.Message);

                    myClientSocket.Shutdown(SocketShutdown.Both);

                    myClientSocket.Close();

                    break;

                }

            }

        }

    }

클라이언트:
class Program

    {

        private static byte[] result = new byte[1024];

        static void Main(string[] args)

        {

            // IP 

            IPAddress ip = IPAddress.Parse("127.0.0.1");

            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try

            {

                clientSocket.Connect(new IPEndPoint(ip, 8885)); // IP 

                Console.WriteLine(" ");

            }

            catch

            {

                Console.WriteLine(" , !");

                return;

            }

            // clientSocket 

            int receiveLength = clientSocket.Receive(result);

            Console.WriteLine(" :{0}",Encoding.ASCII.GetString(result,0,receiveLength));

            //  clientSocket  

            for (int i = 0; i < 10; i++)

            {

                try

                {

                    Thread.Sleep(1000);    // 1 

                    string sendMessage = "client send Message Hellp" + DateTime.Now;

                    clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));

                    Console.WriteLine(" :{0}" + sendMessage);

                }

                catch

                {

                    clientSocket.Shutdown(SocketShutdown.Both);

                    clientSocket.Close();

                    break;

                }

            }

            Console.WriteLine("");

            Console.ReadLine();

        }

    }

좋은 웹페이지 즐겨찾기