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: