Linux网络编程-客户端与服务器端通信(Echo)

  Linux网络编程-客户端与服务器端通信  这里已经详细介绍了服务器与客户端之间的信息交互。本章将继续介绍服务器端回应(Echo)功能展示。
先看看服务器端代码:

###############################simptcpechoserver.c############################

#include <stdio.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>





int main() {

  int ld,sd;

  struct sockaddr_in skaddr;

  struct sockaddr_in from;

  socklen_t addrlen, length;



  char buff[100],send_message[100];

  int n;



  if ((ld = socket (PF_INET, SOCK_STREAM, 0))<0) {

    perror("Problem creating socket/n");

    exit(1);

  }



  skaddr.sin_family = AF_INET;

  skaddr.sin_addr.s_addr = htonl (INADDR_ANY);

  skaddr.sin_port = htons(0);



  if(bind(ld,(struct sockaddr *)&skaddr, sizeof (skaddr))<0){

    perror("Problem binding/n");

    exit(0);

  }



  length = sizeof (skaddr);

  if (getsockname(ld, (struct sockaddr *)&skaddr, &length) <0) {

     perror("Error getsockname/n");

     exit(1);

  }

  printf("The Server passive socket port number is %d/n",

ntohs(skaddr.sin_port));



  if (listen(ld,5)<0) {

     perror("Error calling listen/n");

     exit(1);

  }



  while (1) {

    printf("Ready for a connection ... /n");

    addrlen=sizeof(skaddr);

    if((sd = accept (ld, (struct sockaddr*) &from, &addrlen)) <0) {

       perror("Problem with accept call/n");

       exit(1);

    }



   printf("Got a connect - processing .../n");

   length = sizeof (skaddr);

   if (getsockname (sd, (struct sockaddr*)&skaddr, &length)<0) {

      perror ("Error getsockname/n");

      exit(1);

   }



   printf("The active server port number is %d/n", ntohs

(skaddr.sin_port));

   printf("The active server IP ADDRESS is %s/n" ,inet_ntoa

(skaddr.sin_addr));



  printf("The client port number is %d/n", ntohs(from.sin_port));

  printf("The client IP ADDRESS is %s/n",inet_ntoa(from.sin_addr));



  while ((n=read(sd,buff,100))>0) {

/* printf("%s/n","Client say:");

    write (1,buff,n);

    printf("%s/n","Server say:");

    fgets(send_message,100,stdin);

    write (sd,send_message,strlen(send_message));

*/


    write (sd,buff,n);

 }



  printf("Done with connection -closing/n/n/n");

  close (sd);

  }

}

其实这里跟前面那篇文章里面的server端代码并没有重大的改变,只是这里注释掉了一些代码。注释掉的代码完成的功能是打印从客户端接受的数据以及重新让用户输入客户端的数据。结果只是简单的返回从客户端接受到的数据。所以客户端还是原来的代码。不需要作任何修改。
执行结果:
server:
liceven@liceven-laptop:~/Desktop/linuxweb$ gcc -o tcpechoserver simptcpechoserver.c
liceven@liceven-laptop:~/Desktop/linuxweb$ ./tcpechoserver
The Server passive socket port number is 59968
Ready for a connection ...
Got a connect - processing ...
The active server port number is 59968
The active server IP ADDRESS is 127.0.0.1
The client port number is 44760
The client IP ADDRESS is 127.0.0.1
client:
liceven@liceven-laptop:~/Desktop/linuxweb$ ./simtcpclient 127.0.0.1 59968
Client says:
221
Server says:
221


你可能感兴趣的:(Linux网络编程-客户端与服务器端通信(Echo))