Home > other >  Questions about the socket network programming.
Questions about the socket network programming.

Time:11-02

School just to learn the socket network programming, I want to set up a server to send messages to each other, the effect of this is my code
Server:
#include
#include
#include
#include
#include
#include
#include

8000//port # define SERV_PORT macro definition
Int main (void)
{
FILE *fp;
Int LFD, CFD, len;
Struct sockaddr_in serv_addr clin_addr;
Socklen_t clin_len;
Char buf [1024].
Char MSG [1024].
Memset (MSG, 0, 1024);
Memset (buf, 0, 1024);

//AF_INET: ipv4 SOCK_STREAM: 0: stream protocol TCP
LFD=socket (AF_INET SOCK_STREAM, 0).

Serv_addr. Sin_family=AF_INET;
Serv_addr. The sin_addr. S_addr=htonl (INADDR_ANY);//host to net long
Serv_addr. Sin_port=htons (SERV_PORT);//host to net short network sequence: big end store
//IP + port
Bind (LFD, (struct sockaddr *) & amp; Serv_addr, sizeof (serv_addr));
Listen (LFD, 128);
Clin_len=sizeof (clin_addr);
CFD=accept (LFD, (struct sockaddr *) & amp; Clin_addr, & amp; Clin_len);
Strcpy (buf, "Fred 's server");
Write (CFD, buf, sizeof (buf) + 1);
Do {
Memset (buf, 0, 999);
Len=read (CFD, buf, sizeof (buf));
//the standard output
//write (STDOUT_FILENO, buf, len);
Printf (" the Receive: % s \ n ", buf);
Printf (" do input MSG you want to send \ n ");
[^ \ n] the scanf (" % s ", MSG);
Write (CFD, MSG, sizeof (MSG) + 1);
}while(1);
return 0;
}


Client:
#include
#include
#include
#include
#include
#include
#include



Int main (void)
{

Int sockfd;
Char sendline [100].
Struct sockaddr_in serveaddr;

Sockfd=socket (AF_INET SOCK_STREAM, 0).

Bzero (& amp; Serveaddr, sizeof (serveaddr));

Serveaddr. Sin_family=AF_INET;

Serveaddr. Sin_port=htons (8000);

Inet_pton (AF_INET, "192.168.2.10", & amp; (serveaddr sin_addr));
The connect (sockfd, (struct sockaddr *) & amp; Serveaddr, sizeof (serveaddr));
Do {
Memset (sendline, 0, 100);
Read (sockfd, sendline, sizeof (sendline));
Printf (" % s \ n ", sendline);
Memset (sendline, 0, 100);
Printf (" do input MSG you want to send \ n ");
[^ \ n] the scanf (" % s ", sendline);
Write (sockfd, sendline, strlen (sendline) + 1);
}while(1);
}

Just a connection has good results, and then enter a line weeks began to an infinite loop,
I just want to send one side then the other end can be a back after you receive is waiting to receive messages from each other and then start sending information, don't know what to do


  • Related