Simple console chat program (C socket programming)

Source: Internet
Author: User
Tags socket error htons
First, let's take a look. Program Code :

/* Server. C */
# Include <stdio. h>
# Include <winsock2.h>/* for socket */
# Include <time. h>/* for clock ();*/

# Define listen_port 5500/* listening port */

# Pragma comment (Lib, "ws2_32.lib")/* import library for socket */

Int main ()
{
Hostent * host_entry;
Char host_name [2, 256];
Int N;
Struct wsadata;
Int sock, length;
Struct sockaddr_in srvaddr;
Struct sockaddr tcpaddr;
Int msgsock;
Char Buf [1024];
Int rval, Len;
Char C;
Char data [1024];
Int I;

Clock_t t_start = clock ();

If (maid (0x0101, & wsadata) = 0)/* initialize */
{
N = gethostname (host _name, 256);/* Get localhost name */
Host_entry = gethostbyname (host_name);/* Get localhost address */
If (host_entry! = NULL)/* print localhost address */
{
Printf ("% d. % d \ n ",
Host_entry-> h_addr_list [0] [0] & 0x00ff,
Host_entry-> h_addr_list [0] [1] & 0x00ff,
Host_entry-> h_addr_list [0] [2] & 0x00ff,
Host_entry-> h_addr_list [0] [3] & 0x00ff );

}
Printf ("establish connecting & listening... \ n ");
Sock = socket (af_inet, sock_stream, 0);/* Create socket */
If (sock <0)
{
Printf ("Open socket error \ n ");
Exit (1 );
}

Memset (& srvaddr, 0, sizeof (struct sockaddr ));
Srvaddr. sin_family = af_inet;
Srvaddr. sin_port = htons (listen_port );
If (BIND (sock, (struct sockaddr *) & srvaddr, sizeof (srvaddr) <0)/* Bind Address */
{
Printf ("socket BIND error. \ n ");
Exit (1 );
}

Length = sizeof (srvaddr );
If (getsockname (sock, (struct sockaddr *) & srvaddr, & length) <0)
{
Printf ("Get sock name error. \ n ");
Exit (1 );
}

Printf ("listening port: # % d \ n", ntohs (srvaddr. sin_port ));

Listen (sock, 5);/* listening */
Len = sizeof (struct sockaddr );

Do {
Msgsock = accept (sock, (struct sockaddr *) & tcpaddr, (int *) & Len);/* Create accept sock */
If (msgsock =-1)
{
Printf ("error accept. \ n ");
}
Else
Do {
If (clock ()-t_start> 20000)
{
Closesocket (msgsock );
Wsacleanup ();
Printf ("time out. \ n ");
Exit (0 );
}
Memset (BUF, 0, sizeof (BUF ));
If (rval = Recv (msgsock, Buf, 1024, 0) <0)/* receive MSG */
{
Printf ("Recv sock MSG error. \ n ");
}
If (rval = 0)
{
Printf ("ending connecting. \ n ");
Closesocket (msgsock );
Wsacleanup ();
Exit (1 );
}
Else
{
T_start = clock ();
Printf ("---> % s \ n", Buf );
}
Memset (data, 0, 1024 );
I = 0;
C = getchar ();
While (C! = 10)
{
Data [I ++] = C;
C = getchar ();
}
Data [I] = '\ 0 ';
Send (msgsock, Data, sizeof (data), 0);/* Send MSG */
T_start = clock ();
If (strcmp (BUF, "bye") = 0)/* If send "bye" then end session */
{
Closesocket (msgsock );
Wsacleanup ();
Exit (1 );
}


} While (rval! = 0 );
Closesocket (msgsock );
} While (1 );
}
Wsacleanup ();

Return 0;
}

/* Client. C */

# Include <stdio. h>
# Include <winsock2.h>

# Pragma comment (Lib, "ws2_32.lib ")

Int main (INT argc, char * argv [])
{
Hostent * host_entry;
Char host_name [2, 256];
Int N;
Struct wsadata;
Int sock;
Struct sockaddr_in srvaddr;
Struct hostent * HP;
Char data [1024];
Char C;
Int I = 0;

If (argc <3)
{
Printf ("Usage: % s IP port \ n", argv [0]);
Exit (1 );
}

If (wsastartup (0x0101, & wsadata) = 0)
{
N = gethostname (host_name, 256 );
Host_entry = gethostbyname (host_name );
If (host_entry! = NULL)
{
Printf ("% d. % d \ n ",
Host_entry-> h_addr_list [0] [0] & 0x00ff,
Host_entry-> h_addr_list [0] [1] & 0x00ff,
Host_entry-> h_addr_list [0] [2] & 0x00ff,
Host_entry-> h_addr_list [0] [3] & 0x00ff );

}

Sock = socket (af_inet, sock_stream, 0 );
If (sock <0)
{
Printf ("socket create error. \ n ");
Exit (1 );
}
Srvaddr. sin_family = af_inet;
HP = gethostbyname (argv [1]);
If (HP = 0)
{
Printf ("unknow HOST: % s \ n", argv [1]);
Exit (1 );
}
Memcpy (char *) & srvaddr. sin_addr, (char *) HP-> h_addr, HP-> h_length );
Srvaddr. sin_port = htons (unsigned short) atoi (argv [2]);

If (connect (sock, (struct sockaddr *) & srvaddr, sizeof (srvaddr) <0)/* connect server */
{
Printf ("Connect server error. \ n ");
Exit (1 );
}

While (1)
{
Memset (data, 0, 1024 );
I = 0;
C = getchar ();
While (C! = 10)
{
Data [I ++] = C;
C = getchar ();
}
Data [I] = '\ 0 ';
If (send (sock, Data, sizeof (data), 0) <0)/* Send MSG to server */
{
Printf ("send data error. \ n ");
Exit (1 );
}

If (Recv (sock, Data, 1024, 0)/* receive MSG from server */
{
Printf ("-----> % s \ n", data );
}
If (strcmp (data, "bye") = 0)
{
Closesocket (sock );
Printf ("Connecting close. \ n ");
Wsacleanup ();
Exit (0 );
}
}
}

wsacleanup ();
return 0;
}< br> the above program is compiled in VC ++ 6.0. Start the command line, first start the server server.exe, and listen on port 5500. After the client starts with client.exe IP 5500 (the IP address is the IP address of the server), it can send a message to the server, and then the server receives the message and displays it, in addition, the server can send a message to the client. After receiving the message, the client also sends the message. The above program is very simple. It is just a demo program. The client sends messages first, then the server sends messages, and then the client sends messages .... they cannot send messages consecutively. When the server does not send or receive information for 20 seconds, the socket connection is automatically disconnected. If you are interested, you can improve it so that both parties can freely send and receive information.

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.