Remove Ads

Share on Facebook Share on Twitter

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Socket Server
#1
Here's a short socket example for C++. It listens then exits when a connection is found. Later I might make a client that sends and recieves messages.
[code]
/*This is a server, not a client.
Telnet will be the client.
By Scorch for Computertech*/
#include <iostream>
#include <winsock2.h>

int main()
{
WSAData wsadata;
WORD Version = MAKEWORD(2, 1);//This is the standard

WSAStartup(Version, &wsadata);

SOCKADDR_IN ex;//This has a struct called addr
short length = sizeof(ex);

SOCKET Listen = socket(AF_INET, SOCK_STREAM, NULL);//SOCK_STREAM is basically TCP while SOCK_DGRAM is UDP
SOCKET Connect = socket(AF_INET, SOCK_STREAM, NULL);

ex.sin_addr.s_addr = inet_addr("127.0.0.1");//ip address
ex.sin_family = AF_INET;//Address family
ex.sin_port = htons(100);//port, doesn't usually matter
//Use htons() with sin_port for byte ordering

bind(Listen,(SOCKADDR*)&ex, sizeof(ex));

listen(Listen, SOMAXCONN);//Tell program to wait for connections

for(;Wink
{
std::cout<<"Listening...";
if(Connect = accept(Listen, (SOCKADDR*)&ex, (int*)&length))
{
std::cout<<"\nConnection accepted!\n";
break;
}
}
std::cin.get();
return 0;
}
[/code]

To test for a connection i'll use telnet. Windows xp users should have it by default.
Vistsa/7 users should go to control panel->programs and features->Turn on...-> Select telnet client.

Now follow this .gif to test.
[Image: http://i992.photobucket.com/albums/af47/...Telnet.gif]
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)