วันพุธที่ 11 มีนาคม พ.ศ. 2558

visual c++ socket

Program Server
เมื่อกดปุ่ม "Generate number & Send data" โปรแกรม Server จะ Random เลขมา 10 ตัว (ไม่เกิน 4 หลัก) หลักจากนั้นนำมาเรียงจาก น้อยไปมาก ให้เห็นบนโปรแกรม 
สามารถกดปุ่ม "Generate number & Send data" ได้ไม่จำกัดจำนวนครั้ง

Program Client
เมื่อได้ข้อมูลจาก Socket ให้นำตัวเลขทั้ง 10 ตัวที่เรียงจากน้อยไปมาก มาแบ่งครึ่งเพื่อแสดงผล ตามรูปภาพ




server
 #pragma once  
 #include <stdlib.h>   /* srand, rand */  
 #include <time.h>    /* time */  
 #include <algorithm>     /* sort */  
 #include <winsock2.h>     /* socket */  
 #include <Ws2tcpip.h>     /* socket */  
 #pragma comment(lib, "Ws2_32.lib")  
 #define WIN32_LEAN_AND_MEAN  
 #define DEFAULT_BUFLEN 512  
 #define DEFAULT_PORT 27015  
 namespace SocketSortNumber {  
      using namespace System;  
      using namespace System::ComponentModel;  
      using namespace System::Collections;  
      using namespace System::Windows::Forms;  
      using namespace System::Data;  
      using namespace System::Drawing;  
      using namespace std;  
      using namespace Runtime::InteropServices;  
      /// <summary>  
      /// Summary for Form1  
      /// </summary>  
      public ref class Form1 : public System::Windows::Forms::Form  
      {  
      public:  
           Form1(void)  
           {  
                InitializeComponent();  
                //  
                //TODO: Add the constructor code here  
                //  
           }  
      protected:  
           /// <summary>  
           /// Clean up any resources being used.  
           /// </summary>  
           ~Form1()  
           {  
                if (components)  
                {  
                     delete components;  
                }  
           }  
      private: System::Windows::Forms::Button^ button1;  
      protected:   
      private: System::Windows::Forms::TextBox^ textBox1;  
      private: System::Windows::Forms::Label^ label1;  
      private: System::Windows::Forms::Label^ label2;  
      private: System::Windows::Forms::TextBox^ textBox2;  
      private: System::Windows::Forms::Label^ label3;  
      private:  
           /// <summary>  
           /// Required designer variable.  
           /// </summary>  
           System::ComponentModel::Container ^components;  
 #pragma region Windows Form Designer generated code  
           /// <summary>  
           /// Required method for Designer support - do not modify  
           /// the contents of this method with the code editor.  
           /// </summary>  
           void InitializeComponent(void)  
           {  
                this->button1 = (gcnew System::Windows::Forms::Button());  
                this->textBox1 = (gcnew System::Windows::Forms::TextBox());  
                this->label1 = (gcnew System::Windows::Forms::Label());  
                this->label2 = (gcnew System::Windows::Forms::Label());  
                this->textBox2 = (gcnew System::Windows::Forms::TextBox());  
                this->label3 = (gcnew System::Windows::Forms::Label());  
                this->SuspendLayout();  
                //   
                // button1  
                //   
                this->button1->Location = System::Drawing::Point(60, 57);  
                this->button1->Name = L"button1";  
                this->button1->Size = System::Drawing::Size(210, 23);  
                this->button1->TabIndex = 0;  
                this->button1->Text = L"Generate number and Send data";  
                this->button1->UseVisualStyleBackColor = true;  
                this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);  
                //   
                // textBox1  
                //   
                this->textBox1->Location = System::Drawing::Point(27, 130);  
                this->textBox1->Name = L"textBox1";  
                this->textBox1->Size = System::Drawing::Size(278, 20);  
                this->textBox1->TabIndex = 1;  
                //   
                // label1  
                //   
                this->label1->AutoSize = true;  
                this->label1->Location = System::Drawing::Point(35, 111);  
                this->label1->Name = L"label1";  
                this->label1->Size = System::Drawing::Size(87, 13);  
                this->label1->TabIndex = 2;  
                this->label1->Text = L"Random Number";  
                //   
                // label2  
                //   
                this->label2->AutoSize = true;  
                this->label2->Location = System::Drawing::Point(35, 175);  
                this->label2->Name = L"label2";  
                this->label2->Size = System::Drawing::Size(59, 13);  
                this->label2->TabIndex = 3;  
                this->label2->Text = L"Min -> Max";  
                //   
                // textBox2  
                //   
                this->textBox2->Location = System::Drawing::Point(27, 192);  
                this->textBox2->Name = L"textBox2";  
                this->textBox2->Size = System::Drawing::Size(278, 20);  
                this->textBox2->TabIndex = 4;  
                //   
                // label3  
                //   
                this->label3->AutoSize = true;  
                this->label3->Location = System::Drawing::Point(27, 236);  
                this->label3->Name = L"label3";  
                this->label3->Size = System::Drawing::Size(0, 13);  
                this->label3->TabIndex = 5;  
                //   
                // Form1  
                //   
                this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);  
                this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;  
                this->ClientSize = System::Drawing::Size(334, 261);  
                this->Controls->Add(this->label3);  
                this->Controls->Add(this->textBox2);  
                this->Controls->Add(this->label2);  
                this->Controls->Add(this->label1);  
                this->Controls->Add(this->textBox1);  
                this->Controls->Add(this->button1);  
                this->Name = L"Form1";  
                this->Text = L"Server";  
                this->ResumeLayout(false);  
                this->PerformLayout();  
           }  
 #pragma endregion  
      private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {  
                     int number [10] = {};  
                     int iResult = 0;        
                     int recvbuflen = DEFAULT_BUFLEN;  
                     WSADATA wsaData;  
                     SOCKET ListenSocket = INVALID_SOCKET;  
                     sockaddr_in service;  
                     randdomNumber(number,number+10);  
                     String^ str = ToString(number,number+10);  
                     textBox1->Text = str;  
                     std::sort(number,number+10);  
                     str = ToString(number,number+10);  
                     textBox2->Text = str;  
                     iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);  
                     if (iResult != NO_ERROR) {  
                          label3->Text = ("Error at WSAStartup()");   
                     }  
                     ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  
                     if (ListenSocket == INVALID_SOCKET) {  
                          label3->Text = ("socket function failed with error: %u");  
                          WSACleanup();  
                     }  
                     service.sin_family = AF_INET;  
                     service.sin_addr.s_addr = inet_addr("127.0.0.1");  
                     service.sin_port = htons(27015);  
                     iResult = bind(ListenSocket, (SOCKADDR *) &service, sizeof (service));  
                     if (iResult == SOCKET_ERROR) {  
                          label3->Text = ("bind failed with error ");  
                          closesocket(ListenSocket);  
                          WSACleanup();  
                     }  
                     if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR){  
                          label3->Text = ("listen function failed with error: ");  
                          iResult = closesocket(ListenSocket);  
                          WSACleanup();  
                     }  
                     ListenSocket = accept(ListenSocket, NULL, NULL);  
                     if (ListenSocket == INVALID_SOCKET) {  
                          label3->Text = ("accept failed with error:");  
                          closesocket(ListenSocket);  
                          WSACleanup();  
                     } else  
                          label3->Text = ("Client connected.");       
                     IntPtr p = Marshal::StringToHGlobalAnsi(str);  
                     char *sendbuf = static_cast<char*>(p.ToPointer());  
                     send(ListenSocket, sendbuf, (int)strlen(sendbuf), 0 );  
                     WSACleanup();  
                 }   
                 void randdomNumber(int* first, int* last){  
                      srand(time(NULL));  
                      int * current = first;  
                      while (current != last) {  
                          *current = rand() % 10000; //Generate an integer between 0 and 9999  
                          ++current;  
                     }  
                 }  
                 String^ ToString(const int* first, const int* last){  
                     String^ str = "";  
                     const int * current = first;  
                     while (current != last) {  
                          str += Convert::ToString(*current);  
                          ++current;   // increment pointer  
                          if (current != last) str += ",";   
                     }  
                     return str;  
                 }  
 };  
 }  


client
 #pragma once  
 #include <winsock2.h>     /* socket */  
 #include <Ws2tcpip.h>     /* socket */  
 #pragma comment(lib, "Ws2_32.lib")  
 #define WIN32_LEAN_AND_MEAN  
 #define DEFAULT_BUFLEN 512  
 #define DEFAULT_PORT 27015  
 namespace client {  
      using namespace System;  
      using namespace System::ComponentModel;  
      using namespace System::Collections;  
      using namespace System::Windows::Forms;  
      using namespace System::Data;  
      using namespace System::Drawing;  
      /// <summary>  
      /// Summary for Form1  
      /// </summary>  
      public ref class Form1 : public System::Windows::Forms::Form  
      {  
      public:  
           Form1(void)  
           {  
                InitializeComponent();  
                //  
                //TODO: Add the constructor code here  
                //  
           }  
      protected:  
           /// <summary>  
           /// Clean up any resources being used.  
           /// </summary>  
           ~Form1()  
           {  
                if (components)  
                {  
                     delete components;  
                }  
           }  
      private: System::Windows::Forms::Timer^ timer1;  
      private: System::Windows::Forms::Label^ label1;  
      private: System::Windows::Forms::Label^ label2;  
      private: System::Windows::Forms::Label^ label3;  
      private: System::Windows::Forms::DataGridView^ dataGridView1;  
      private: System::Windows::Forms::Label^ label4;  
      protected:   
      private: System::ComponentModel::IContainer^ components;  
      private:  
           /// <summary>  
           /// Required designer variable.  
           /// </summary>  
 #pragma region Windows Form Designer generated code  
           /// <summary>  
           /// Required method for Designer support - do not modify  
           /// the contents of this method with the code editor.  
           /// </summary>  
           void InitializeComponent(void)  
           {  
                this->components = (gcnew System::ComponentModel::Container());  
                this->timer1 = (gcnew System::Windows::Forms::Timer(this->components));  
                this->label1 = (gcnew System::Windows::Forms::Label());  
                this->label2 = (gcnew System::Windows::Forms::Label());  
                this->label3 = (gcnew System::Windows::Forms::Label());  
                this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView());  
                this->label4 = (gcnew System::Windows::Forms::Label());  
                (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dataGridView1))->BeginInit();  
                this->SuspendLayout();  
                //   
                // timer1  
                //   
                this->timer1->Enabled = true;  
                this->timer1->Interval = 250;  
                this->timer1->Tick += gcnew System::EventHandler(this, &Form1::timer1_Tick);  
                //   
                // label1  
                //   
                this->label1->AutoSize = true;  
                this->label1->Location = System::Drawing::Point(105, 66);  
                this->label1->Name = L"label1";  
                this->label1->Size = System::Drawing::Size(0, 13);  
                this->label1->TabIndex = 0;  
                //   
                // label2  
                //   
                this->label2->AutoSize = true;  
                this->label2->Location = System::Drawing::Point(37, 66);  
                this->label2->Name = L"label2";  
                this->label2->Size = System::Drawing::Size(27, 13);  
                this->label2->TabIndex = 1;  
                this->label2->Text = L"Max";  
                //   
                // label3  
                //   
                this->label3->AutoSize = true;  
                this->label3->Location = System::Drawing::Point(40, 174);  
                this->label3->Name = L"label3";  
                this->label3->Size = System::Drawing::Size(24, 13);  
                this->label3->TabIndex = 2;  
                this->label3->Text = L"Min";  
                //   
                // dataGridView1  
                //   
                this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize;  
                this->dataGridView1->Location = System::Drawing::Point(156, 50);  
                this->dataGridView1->Name = L"dataGridView1";  
                this->dataGridView1->Size = System::Drawing::Size(10, 168);  
                this->dataGridView1->TabIndex = 3;  
                //   
                // label4  
                //   
                this->label4->AutoSize = true;  
                this->label4->Location = System::Drawing::Point(193, 65);  
                this->label4->Name = L"label4";  
                this->label4->Size = System::Drawing::Size(0, 13);  
                this->label4->TabIndex = 4;  
                //   
                // Form1  
                //   
                this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);  
                this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;  
                this->ClientSize = System::Drawing::Size(284, 261);  
                this->Controls->Add(this->label4);  
                this->Controls->Add(this->dataGridView1);  
                this->Controls->Add(this->label3);  
                this->Controls->Add(this->label2);  
                this->Controls->Add(this->label1);  
                this->Name = L"Form1";  
                this->Text = L"Client";  
                (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->dataGridView1))->EndInit();  
                this->ResumeLayout(false);  
                this->PerformLayout();  
           }  
 #pragma endregion  
      private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) {  
                int Result;  
                WSADATA wsaData;  
                SOCKET SocketNumber = INVALID_SOCKET;  
                struct sockaddr_in clientService;   
                int recvbuflen = DEFAULT_BUFLEN;  
                char recvbuf[DEFAULT_BUFLEN] = "";  
                Result = WSAStartup(MAKEWORD(2,2), &wsaData);  
                if (Result != NO_ERROR) {  
                     label1->Text = ("WSAStartup failed with error:" + Result);  
                }  
                SocketNumber = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  
                if (SocketNumber == INVALID_SOCKET) {  
                     label1->Text = ("socket failed with error: " + WSAGetLastError());  
                     WSACleanup();  
                }  
                clientService.sin_family = AF_INET;  
                clientService.sin_addr.s_addr = inet_addr( "127.0.0.1" );  
                clientService.sin_port = htons( DEFAULT_PORT );  
                Result = connect( SocketNumber, (SOCKADDR*) &clientService, sizeof(clientService) );  
                if (Result == SOCKET_ERROR) {  
                     //label1->Text = ("connect failed with error: " + WSAGetLastError());  
                     closesocket(SocketNumber);  
                     WSACleanup();  
                 }  
                do {  
                     Result = recv(SocketNumber, recvbuf, recvbuflen, 0);  
                     if ( Result > 0 ){  
                     String^ msg = gcnew String(recvbuf);  
                     array<Char> ^sep = gcnew array<Char>{','};  
                     array<String^>^result;  
                     result = msg->Split( sep, StringSplitOptions::RemoveEmptyEntries );  
                     String^ tmp = "";  
                     for(int i = (result->Length)/2-1;i >= 0;i-- )  
                          tmp += result[i] + "\n\n";  
                     label1->Text = tmp;  
                     tmp = "";  
                     for(int i = (result->Length)/2;i < result->Length;i++ )  
                          tmp += result[i] + "\n\n";  
                     label4->Text = tmp;  
                     memset(recvbuf, 0, DEFAULT_BUFLEN);  
                     }else if ( Result == 0 )  
                          label1->Text = ("Connection closed");    
                     else  
                          //label1->Text = ("recv failed with error: " + WSAGetLastError());  
                          ;  
                } while( Result > 0 );  
            }  
      };  
 }