Session communication program

Source: Internet
Author: User
Tags htons
This instance completes a simple session communication process between the server and the client. you must install the TCP/IP protocol on the host and set the IP address. the server and client use different port numbers of the same host. The server uses port numbers 2000 and the client uses port numbers 3000.
The server program runs first. First, initialize WinSock, then create a socket, bind it to port 2000, then listen on port 2000, and enter the waiting state. after running the client, first initialize WinSock, then create a socket, and then try to connect to the server. once the connection is established, communication can be performed between the server and the client. the client prompts you to enter a number. For example, if you enter 50, the client sends 50 strings from "data0" to "data49" and enters 0 to exit.

Server. cpp:
######################################## #####################
# Include "Winsock. H"
# Include "windows. H"
# Include "stdio. H"
# Pragma comment (Lib, "wsock32.lib ")
# Define recv_port 2000
# Define send_port 3000

Socket sock, sock1;
Sockaddr_in serveraddr;
Sockaddr_in clientaddr;
Int addrlen;

DWORD startsock ()
{
Wsadata;
If (wsastartup (makeword (2, 2), & wsadata )! = 0) // initialize the socket
// Wsastartup: load the corresponding version of WinSock DLL.
// P1: Version XY, generated using makeword (x, y), x-high byte, Y-low byte
// P2: pointer to the wsadata structure and receives the Winsock database version information.
{
Printf ("Sock init fail! /N ");
Return (-1 );
}
Return (1 );
}

DWORD createsocket ()
{
Sock = socket (af_inet, sock_stream, 0); // create a socket
// Socket: Create a socket
// P1: network type, generally af_inet, indicating communication in the Internet Domain
// P2: socket type, sock_stream (Session socket), sock_dgram (datagram socket), sock_seqpacket,
// Sock_raw (original socket), sock_rdm.
// P3: network protocol. The value 0 indicates TCP/IP.
// Wsanotinitidlised error: Winsock library not loaded
If (sock = socket_error)
{
Printf ("Sock create fail! /N ");
Wsacleanup ();
Return (-1 );
}
Serveraddr. sin_family = af_inet; // fill in the server address and port number
Serveraddr. sin_addr.s_addr = htonl (inaddr_any); // any IP Address
Serveraddr. sin_port = htons (recv_port); // port on the IP address

If (BIND (sock, (struct sockaddr far *) & serveraddr, sizeof (serveraddr) = socket_error)
// BIND: Write a local address and bind a socket.
// P1: A handle not bound to a socket.
// P2: socket address structure.
// Wsaeaddrinuse error: Another process has been bound to the local IP address and port number.
{
Printf ("Bind is the error ");
Return (-1 );
}
Return (1 );
}

DWORD connectprocess ()
{
Char buff [80];
Addrlen = sizeof (sockaddr_in );
If (Listen (sock, 5) <0)
// Listen: listener.
// P1: A handle bound to an unconnected socket.
// P2: the maximum length of the queue waiting for connection.
// A wsaeconnerefused error may occur when an extra connection request is sent.
{
Printf ("Listen error ");
Return (-1 );

}
Printf ("listening.../N ");
For (;;)
{
Sock1 = accept (sock, (struct sockaddr far *) & clientaddr, & addrlen );
// Sock: accept a connection on the specified socket
// P1: Set the word-based handle. The socket has listened for the connection after listen.
// P2: Address of the sockaddr_in structure of the connection requester.
// P3: length of the sockaddr_in Structure
For (;;)
{
Memset (buff, 0, 80 );
If (Recv (sock1, buff, 80, 0) <= 0)
// Recv: receives data.
// P1: Socket handle.
// P2: receiving buffer.
// P3: the length of the receiving buffer.
// P4: Call execution method.
// Returns the actual number of bytes sent.
{
Break;
}
Printf (buff );
// Printf ("/N ");
}
}
}

Int main ()
{
If (startsock () =-1)
Return (-1 );
If (createsocket () =-1)
Return (-1 );
If (connectprocess () =-1)
Return (-1 );
Return (1 );
}

Client. cpp
######################################## ##########################
# Include "Winsock. H"
# Include "windows. H"
# Include "stdio. H"
# Pragma comment (Lib, "wsock32.lib ")
# Define recv_port 2000
# Define send_port 3000
# Define serveraddr "192.168.100.148"

Socket sock;
Sockaddr_in serveraddr;

DWORD startsock ()
{
Wsadata;
If (wsastartup (makeword (2, 2), & wsadata )! = 0) // initialize the socket
// Wsastartup: load the corresponding version of WinSock DLL.
// P1: Version XY, generated using makeword (x, y), x-high byte, Y-low byte
// P2: pointer to the wsadata structure and receives the Winsock database version information.
{
Printf ("Sock init fail! /N ");
Return (-1 );
}
Serveraddr. sin_family = af_inet; // fill in the server address and port number
Serveraddr. sin_addr.s_addr = inet_addr (serveraddr );
Serveraddr. sin_port = htons (recv_port );
Return (1 );
}

DWORD createsocket ()
{
Sock = socket (af_inet, sock_stream, 0); // create a socket
// Socket: Create a socket
// P1: network type, generally af_inet, indicating communication in the Internet Domain
// P2: socket type, sock_stream (Session socket), sock_dgram (datagram socket), sock_seqpacket,
// Sock_raw (original socket), sock_rdm.
// P3: network protocol. The value 0 indicates TCP/IP.
// Wsanotinitidlised error: Winsock library not loaded
If (sock = socket_error)
{
Printf ("Sock create fail! /N ");
Wsacleanup ();
Return (-1 );
}

Return (1 );
}

DWORD callserver ()
{
Createsocket ();
If (connect (sock, (struct sockaddr *) & serveraddr, sizeof (serveraddr) = socket_error)
// CONNECT: establish a connection with a server
// P1: the handle of an unconnected socket.
// P2: Address of the sockaddr_in structure.
// P3: length of the sockaddr_in Structure
{
Printf ("Connect fail/N ");
Closesocket (sock );
// Closesocket: closes a socket.
Return (-1 );
}
Return (1 );
}

DWORD tcpsend (char data [])
{
Int length;
Length = Send (sock, Data, strlen (data), 0 );
// Send: send data on a socket.
// P1: Socket handle.
// P2: sending buffer.
// P3: number of characters in the sending buffer.
// P4: Call execution method.
// Returns the number of bytes sent.
If (length <= 0)
{
Printf ("send data error! /N ");
Closesocket (sock );
Wsacleanup ();
Return (-1 );
}
Return (1 );
}

Int main ()
{
Char buff [80];
Int num, I;
Startsock ();
While (callserver () =-1 );
Printf ("Connect OK! /N ");
Printf ("press any key to send! ");
Getchar ();
For (;;)
{
Printf ("input the number of message to send: (0-exit )");
Memset (buff, 0, 80 );
Scanf ("% d", & num );
If (Num <= 0)
Break;
For (I = 0; I <num; I ++)
{
Sprintf (buff, "Data % d/N", I );
Printf (buff );
Tcpsend (buff );
Sleep (100 );
}
}
Return (0 );
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.