Post Reply 
Social Buttons
 
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Socket Server
Author Message
Scorch Offline
Intermediate C++
********

Trade Count: (0)
Posts: 83
Joined: Jan 2011
Reputation: 15
Post: #1
Socket Server
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(;;)
    {
        std::cout<<"Listening...";
        if(Connect = accept(Listen, (SOCKADDR*)&ex, (int*)&length))
        {
            std::cout<<"\nConnection accepted!\n";
            break;
        }
    }
    std::cin.get();
    return 0;
}

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: Telnet.gif]
(This post was last modified: 02-16-2011 01:49 AM by Scorch.)
01-31-2011 06:24 AM
Find all posts by this user Quote this message in a reply
Post Reply 


Forum Jump:


User(s) browsing this thread: