473,804 Members | 3,004 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

The problem with sockets using Visual C++ windows form application

Hi,

I'm beginner in Visual C++ so I want to ask you a question. And I'm not good
in English:D
So I have the program which communicates over sockets. The program has to
connect to the server and send and receive data. But when I start the
program, there is one Socketexception - something like the program is unable
to connect to the server or the server didn't answer...
I apologize for my English... Thank you for advice...

I made this code:

private: System::Void Form1_Load(Syst em::Object^ sender, System::EventAr gs^
e) {
try
{
Int32 port = 80;
TcpClient^ client = gcnew TcpClient( "www.centrum.cz ",port );

// Translate the passed message into ASCII and store it as a Byte array.
array<Byte>^dat a = System::Text::E ncoding::ASCII->GetBytes( "GET /
HTTP/1.1\n\n" );

// Get a client stream for reading and writing.
// Stream stream = client->GetStream();

NetworkStream^ stream = client->GetStream();

// Send the message to the connected TcpServer.
stream->Write( data, 0, data->Length );
String^ message;
MessageBox::Sho w( "Sent: {0}", message );

// Receive the TcpServer::resp onse.

// Buffer to store the response bytes.
data = gcnew array<Byte>(256 );

// String to store the response ASCII representation.
String^ responseData = String::Empty;

// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream->Read( data, 0, data->Length );
responseData = System::Text::E ncoding::ASCII->GetString( data, 0, bytes );
MessageBox::Sho w( "Received: {0}", responseData );

// Close everything.
client->Close();
}
catch ( ArgumentNullExc eption^ e )
{
MessageBox::Sho w( e->ToString(),"Ar gumentNullExcep tion: {0}" );
}
catch ( SocketException ^ e )
{
MessageBox::Sho w( e->ToString(),"So cketException: {0}" );
}

}

The same problem I have when I do console application:

// chatik2.cpp : Defines the entry point for the console application.
//
#include <stdafx.h>

#define BUFSIZE 1000

using namespace std;

int main(void)
{
WORD wVersionRequest ed = MAKEWORD(1,1); // Č*slo verze
WSADATA data; // Struktura s info. o knihovně
string text("GET HTTP/1.0\r\n"); // Odes*laný a
přij*maný text
hostent *host; // Vzdálený poč*tač
sockaddr_in serverSock; // Vzdálený "konec potrub*"
int mySocket; // Soket
int port; // Č*slo portu
char buf[BUFSIZE]; // Přij*mac* buffer
int size; // Počet přijatých a odeslaných bytů

// Připrav*me sokety na práci
if (WSAStartup(wVe rsionRequested, &data) != 0)
{
cout << "Nepodařil o se inicializovat sokety" << endl;
// Podle všeho, zde se WSACleanup volat nemus*.
return -1;
}
port = 80;
// Zjist*me info o vzdáleném poč*tači
if ((host = gethostbyname(" www.seznam.cz") ) == NULL)
{
cerr << "*patná adresa" << endl;
WSACleanup();
return -1;
}
// Vytvoř*me soket
if ((mySocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
{
cerr << "Nelze vytvořit soket" << endl;
WSACleanup();
return -1;
}
// Zapln*me strukturu sockaddr_in
// 1) Rodina protokolů
serverSock.sin_ family = AF_INET;
// 2) Č*slo portu, ke kterému se připoj*me
serverSock.sin_ port = 80;
// 3) Nastaven* IP adresy, ke které se připoj*me
memcpy(&(server Sock.sin_addr), host->h_addr, host->h_length);
// Připojen* soketu
if (connect(mySock et, (sockaddr *)&serverSock, sizeof(serverSo ck)) == -1)
{
cerr << "Nelze navázat spojen*" << endl;
WSACleanup();
return -1;
}
// Odeslán* dat
if ((size = send(mySocket, text.c_str(), text.size() + 1, 0)) == -1)
{
cerr << "Problém s odeslán*m dat" << endl;
WSACleanup();
return -1;
}
cout << "Odesláno " << size << endl;
// Př*jem dat
text = "";
while (((size = recv(mySocket, buf, BUFSIZE, 0)) != 0) && (size != -1))
{
cout << "Přijato " << size << endl;
text += buf;
}
if (size == -1)
{
cout << "Nelze přijmout data" << endl;
}
// Uzavřu spojen*
closesocket(myS ocket);
WSACleanup();
cout << endl << text << endl;
return 0;
}

Oct 21 '08 #1
1 3796
The project is done... There was a problem with firewall...
Oct 21 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4967
by: Penn Markham | last post by:
Hello all, I am writing a script where I need to use the system() function to call htpasswd. I can do this just fine on the command line...works great (see attached file, test.php). When my webserver runs that part of the script (see attached file, snippet.php), though, it doesn't go through. I don't get an error message or anything...it just returns a "1" (whereas it should return a "0") as far as I can tell. I have read the PHP...
3
3146
by: jean | last post by:
I am very new to .Net and Visual Basic in general. My goal is to write a Visual Basic .Net DLL that can have its functions and subroutines called from another .Net application. My DLL will not have any kind of user interface. Can I use a Timer Control, A Winsock Control, and Serial Com Port class (The reason I am using this class from some borrowed code, is that I heard that .Net 1.1 does not have a built-in Serial Com Port...
4
7102
by: Ron | last post by:
Greetings, below is a sample app for connecting to a mainframe server using Sockets for the purpose of using FTP service to interact with it from a PC. I got as far as creating the connection. But how do I pass a username and password? How can I change directories? --------------------------------------------- using System;
10
14377
by: Robert Jacobson | last post by:
Hi, I'm develing a COM add-in for Microsoft Word XP that displays a form. I'd like to have the form display using the Windows XP theme. However, neither using a manifest nor calling Application.EnableVisualStyles does the trick. (EnableVisualStyles works but massive instability, probably because the system is trying to theme the Word application itself.) I'm now trying to selectively enable the themes for just my form, or just...
36
2488
by: AussieRules | last post by:
Hi, I want to use the user color scheme to set the color of my forms. I now I have to use the. System.Drawing.SystemColors, but which color is the color of a form background as used in other applications. In the end all I want to do is form1.backcolor = system.whatever.color
20
2892
by: Jason Dravet | last post by:
Some time ago I wrote an application that controls the projectors in our classrooms(turn on, turn off, and volume control). This application is written in VB.net 2003. It was working perfectly until XP SP2 was installed on the PCs. Now when the power on or power off button is pressed the following message is displayed: An unhandled exception has occurred in your application. If you click Continue, the application will ignore this...
0
3473
by: ZR | last post by:
I am writing two applications which needs to (among other things) communicate through network, so one of them is a client and the other one is a server. I have used asynchronous socket examples found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconblockingclientsocketexample.asp as templates (they have to be asynchronous, because application must not freeze if connection fails). I have converted the...
0
1953
by: mandarkraftware | last post by:
Hi All, Let me present you with list of consultants currently available. Name / Job Title Summary Ramchandran/Java 7+ years experience in the field of Software Development. Expertise in full Software Development Life Cycle (SDLC)
5
16394
by: Rajkiran R.B. | last post by:
I want to log in to a website using C# code.. The main aim is to check whether the username and password I provide is correct or not. I used the following code bool somefunction() { string username = textbox1.text;
0
9706
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9577
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10569
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10075
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6847
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5651
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4295
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3815
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.