Build 1 pairs of 1 c\s models

Source: Internet
Author: User
Tags htons

Chatroom.h header file:

CLIENT_MAIN.C:

#include ". /include/chatroom.h "
Client
int main (int argc, char** argv)
{
if (argc!= 2)
return 0;
int socketfd;
Char buff[1000] = {0};
struct sockaddr_in servaddr;
SOCKETFD = socket (af_inet, sock_stream, 0);
servaddr.sin_family = AF_INET;//IV4 protocol
Servaddr.sin_port = htons (8000);//8000 Port
Inet_pton (Af_inet, argv[1], &servaddr.sin_addr);//Specify IP address
if (Connect (socketfd, (struct sockaddr*) &servaddr, sizeof (SERVADDR)) < 0)//linked server
{
printf ("Connect Error:%s (errno:%d) \ n", Strerror (errno), errno);
return 0;
}
while (1)
{
printf ("Enter:");
Fgets (Buff,998,stdin);
Send (Socketfd,buff,strlen (buff), 0);
}
}

SERVER_MAIN.C:

#include. /include/chatroom.h '
//server-side
int main ()
{
 int socket_fd, connect_fd;
 char buff[1000] = {0} ;
 struct sockaddr_in servaddr;
&NBSP;SOCKET_FD = socket (af_inet, sock_stream, 0);//Create a socket
 servaddr.sin_family = af_inet;
  SERVADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
 servaddr.sin_port = htons (8000);
 if bind (socket_fd, (struct sockaddr*) &servaddr,sizeof (servaddr)) = = 1)//socket binding ports and protocols
 {
  printf ("Bind error!\n");/if there is an error, try running
  return 0
 
 listen (socket_fd , 10);//listening socket
 connect_fd = accept (SOCKET_FD, NULL);/Agree link
 while (1)
 {
   if (recv (connect_fd, buff,999,0) = = 0)//Accept Data
   break;//stop looping if a link is broken
  printf ( "get:%s", buff)//output receiving data
 
 close (CONNECT_FD);
 close (SOCKET_FD);
 return 0;
}

Compile the client and server side of the source code, the final results are shown as follows:

To view server IP:


Related Article

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.