1

我必须将我的项目(它使用 Windows 窗体作为简单的 UI)与在服务器模式下运行的第三方程序集成,所以我需要一个套接字。下面是相关代码:

入口点:

 #include "UserInterface1.h"
 #include "PanguConnection.h"


 using namespace std;
 using namespace client;


 int WINAPI WinMain(HINSTANCE hInstance, 
 HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
 {  
    Application::EnableVisualStyles();
    Application::Run(gcnew UserInterface1()); 

    return 0;
 }

插座代码:

#ifndef PANGUCONNECTION_H_INCLUDED
 #define PANGUCONNECTION_H_INCLUDED

 #include "socket_stuff.h" 
 #include "pan_protocol_lib.h"

 //#define SERVER_NAME  "192.0.0.10"
 const int SERVER_PORT = 10363;

 class PanguConnection    
 {
 private:
    long addr;  
    SOCKET sock;
    unsigned long saddr_len;
    struct sockaddr_in saddr;
    char SERVER_NAME [10];

 public:
    PanguConnection();
    void Connection();
    unsigned long hostid_to_address(char *s);   
    void Terminate ();
    int simple_tests(SOCKET sock);
    int general_tests(SOCKET);
    int elevation_test(SOCKET);
    int lookup_test(SOCKET);
    int scan_test(SOCKET);
    int get_and_save_image(SOCKET sock, char *fname);   
 };

 #endif // PANGUCONNECTION_H_INCLUDED

 #include <cstdlib>
 #include <cmath>

 #include <stdio.h>
 #include <stdlib.h>

 #include "PanguConnection.h"

 #include "socket_stuff.h" 
 #include "pan_protocol_lib.h"

 using namespace std;

 PanguConnection::PanguConnection() 
 {
        SERVER_NAME [0] = 'l';
        SERVER_NAME [1] = 'o';
        SERVER_NAME [2] = 'c';
        SERVER_NAME [3] = 'a';
        SERVER_NAME [4] = 'l';
        SERVER_NAME [5] = 'h';
        SERVER_NAME [6] = 'o';
        SERVER_NAME [7] = 's';
        SERVER_NAME [8] = 't';      

 #ifdef _WIN32
    WSAData wsaData;
    if (WSAStartup(MAKEWORD(1, 1), &wsaData)){}

 #endif

        /* First get the numeric IP address of the server */
        addr = hostid_to_address((char *)SERVER_NAME);

        /* Create a communications TCP/IP socket */
        sock = socket(AF_INET, SOCK_STREAM, 0);     

        /* Connect the socket to the remote server */
        saddr.sin_family = AF_INET;
        saddr.sin_addr.s_addr = addr;
        saddr.sin_port = htons(SERVER_PORT);
        saddr_len = sizeof(struct sockaddr_in); 

        int res = connect(sock, (struct sockaddr *)&saddr, saddr_len);  

        /* Start the PANGU network communications protocol */
        pan_protocol_start(sock);

        int res1 = simple_tests(sock);
        int res2 = general_tests(sock);
        int res3 = elevation_test(sock);
    int res4 =  lookup_test(sock);
    int res5 = scan_test(sock);
    }

    unsigned long PanguConnection::hostid_to_address(char *s)
    {
        struct hostent *host;

        /* Assume we have a dotted IP address ... */
        long result = inet_addr(s);
        if (result != (long)INADDR_NONE) return result;

        /* That failed so assume DNS will resolve it. */
        host = gethostbyname(s);
        return host ? *((long *)host->h_addr_list[0]) : INADDR_NONE;
 }


 int PanguConnection::simple_tests(SOCKET sock)
 {
    int i, status;
    float x, y, z, yaw, pitch, roll;
    char fname[1024];

    /* Initialise the camera position */
    x = 192.257f, y = 192.257f, z = 126.785f;
    yaw = 135.0f, pitch = -25.0f, roll = 0.0f;

    /* Define the field of view we want to use */
    pan_protocol_set_field_of_view(sock, 30.0);

    /* Instruct the viewer to use this position */
    pan_protocol_set_viewpoint_by_angle(sock, x, y, z, yaw, pitch, roll);

    /* Fly towards the model with constant attitude */
    for (i = 0; i < 5; i++)
    {
        /* Set the new position */
        x -= 1.9f, y -= 1.9f, z -= 1.2f;
        pan_protocol_set_viewpoint_by_angle(sock, x, y, z, yaw, pitch, roll);

        /* Get this image */

        status = get_and_save_image(sock, fname);
        if (status) return status;
    }

...省略了其他测试连接的功能

用户界面代码(想法是单击按钮连接开始,并从在服务器模式下运行的第三方程序中检索一些图像):

#pragma once

 #define _WINSOCKAPI_    // stops windows.h including winsock.h
 #include <winsock2.h>
 #include <windows.h>

 #include "PanguConnection.h"


 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;
    using namespace System::IO;


    /// <summary>
    /// Summary for UserInterface1
    /// </summary>
    public ref class UserInterface1 : public System::Windows::Forms::Form
    {
    public:
        UserInterface1(void)
        {
            InitializeComponent();
            //
            //TODO: Add the constructor code here
            //
        }

    protected:
        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        ~UserInterface1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::PictureBox^  pictureBox1;
    private: System::Windows::Forms::Button^  button1;
    protected: 

    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->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
            this->button1 = (gcnew System::Windows::Forms::Button());
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^
(this->pictureBox1))->BeginInit();
            this->SuspendLayout();
            // 
            // pictureBox1
            // 
            this->pictureBox1->BackColor = System::Drawing::SystemColors::ButtonFace;
            this->pictureBox1->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
            this->pictureBox1->Location = System::Drawing::Point(52, 55);
            this->pictureBox1->Name = L"pictureBox1";
            this->pictureBox1->Size = System::Drawing::Size(555, 476);
            this->pictureBox1->TabIndex = 0;
            this->pictureBox1->TabStop = false;
            this->pictureBox1->Click += gcnew System::EventHandler(this, &UserInterface1::pictureBox1_Click);
            // 
            // button1
            // 
            this->button1->Location = System::Drawing::Point(657, 55);
            this->button1->Name = L"button1";
            this->button1->Size = System::Drawing::Size(104, 61);
            this->button1->TabIndex = 1;
            this->button1->Text = L"button1";
            this->button1->UseVisualStyleBackColor = true;
            this->button1->Click += gcnew System::EventHandler(this, &UserInterface1::button1_Click);
            // 
            // UserInterface1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(8, 16);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->BackColor = System::Drawing::SystemColors::ActiveCaptionText;
            this->ClientSize = System::Drawing::Size(802, 596);
            this->Controls->Add(this->button1);
            this->Controls->Add(this->pictureBox1);
            this->Name = L"UserInterface1";
            this->Text = L"UserInterface1";
            (cli::safe_cast<System::ComponentModel::ISupportInitialize^  (this->pictureBox1))->EndInit();
            this->ResumeLayout(false);

        }
 #pragma endregion

    private: System::Void pictureBox1_Click(System::Object^  sender, System::EventArgs^  e) {

             }

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                PanguConnection PC;
             }
    };
 }

编译器不会抱怨任何事情,但程序不能正常工作。套接字根本不起作用,单击按钮时没有任何反应。任何的想法?我真的很感激任何意见。

好的,我已尝试按照您的建议实现它@Mgetz,但似乎仍然存在问题:

#pragma once

using namespace System::Net::Sockets;
using namespace System;

ref class PanguConnect
{
private:
   TcpClient ^mTcpClient; 

public:
    PanguConnect(void);
    void Connection(System::String^ server, Int32 port);  
    void CloseConnection ();
}; 

#include "PanguConnect.h"
using namespace System::Net::Sockets;
using namespace System;

PanguConnect::PanguConnect(void)
{
}

void PanguConnect::Connection(System::String^ server, Int32 port)
    {           
        mTcpClient = gcnew TcpClient(server, port);

    }

void PanguConnect::CloseConnection ()
{
    mTcpClient->Close();
}

用户界面部分:

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
                PanguConnect PC;
                 try{                
                    PC.Connection("localhost",10363);
                    }

                catch(Exception ^e)
                {
                    MessageBox::Show(e->Message);
                }


                try
                {
                    PC.CloseConnection ();
                }

                catch(Exception ^e)
                {
                    MessageBox::Show(e->Message);
                }
             }

我得到的错误是:没有连接,因为目标机器主动拒绝它:127.0.0.1:10363。你调用的对象是空的。:(

4

1 回答 1

0

这个功能实际上是直接在.NET框架中实现的,不需要直接使用winsock,实际上这样做更危险。

using namespace System::Net::Sockets;

public ref class PanguConnection
{
    private:
    System::Net:Sockets::TcpClient mTcpClient;

    public:
    PanguConnection(System::String^ server, Int32 port)
    {
        this->mTcpClient = gcnew System::Net::Sockets::TcpClient(server, port);
    }
}

注意我注意到您为此使用 TCP,所以System::Net::Sockets::TcpClient应该可以

于 2013-07-14T14:41:25.073 回答