서버 모드에서 실행되는 제 3 자 프로그램과 간단한 프로젝트를 위해 Windows Forms를 사용하는 프로젝트를 통합해야하므로 소켓이 필요합니다. 다음은 관련 코드는 다음과 같습니다Windows Forms의 소켓 코드 C++
진입 점 :
소켓 코드#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;
}
};
}
complier는 아무런 불평을하지 않지만 프로그램이 제대로 작동하지 않습니다. 소켓이 단순히 작동하지 않고 버튼을 클릭해도 아무 반응이 없습니다. 아이디어가 있으십니까? 나는 어떤 의견이라도 정말로 고맙게 생각한다.
괜찮아 난 당신이 @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. 개체 참조가 개체의 인스턴스로 설정되지 않았습니다. :(
이 기능은 실제로이 직접 윈속을 사용할 필요가 없으며에 - 사실 그렇게 할 더 위험은 .NET 프레임 워크에 직접 구현되는
.Net 프레임 워크는 [소켓] (http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx?cs- save-lang = 1 & cs-lang = cpp # code-snippet-1) 그냥 사용하지 않는 이유는 무엇입니까? – Mgetz
그래, 그것에 대해 생각해 보았습니다. 그래도 (하지만 Windows Forms에서 사용하기 위해 개발되지는 않았으므로) 구현하려고 시도했습니다. 나는 네가 말하는 것처럼 내가 할 것 같아. 입력을 주셔서 감사합니다 – elrim
응용 프로그램이 winforms 프로젝트로 생성 되었습니까? 그렇다면 아마 순수 CLR로 설정됩니다. – Mgetz