Linux--TCPsocket传输图片

服务器端

/* server端代码:接受Client端发送过来的一个图片 */

#include   <sys/socket.h>
#include   <sys/types.h>
#include   <stdlib.h>
#include   <stdio.h>
#include   <string.h>
#include   <unistd.h>
#include   <error.h>
#include   <netinet/in.h>
#include   <arpa/inet.h>
#define   SER_PORT   9998   
#define   MAX_LEN       256

int main(int argc,char **argv)
{
        int     listensd,connectsd;
        struct sockaddr_in   server;
        struct sockaddr_in   client;
        char    buf[MAX_LEN] = "\0";
        FILE    *fp;
        int     opt = 1;
        if( ( listensd = socket(AF_INET,SOCK_STREAM,0) ) == -1 )
       {
                perror("socket");
                exit(1);
        }
       setsockopt(listensd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
         bzero(&server,sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(SER_PORT);
        server.sin_addr.s_addr = htonl(INADDR_ANY);
         if( bind(listensd,(struct sockaddr *)&server,sizeof(server)) < 0)
        {
                perror("Bind");
                close(listensd);
                exit(1);
        }
         if( listen(listensd,5) == -1 )
        {
                perror("listen");
                close(listensd);
                exit(1);
        }
         if( ( fp = fopen("new1.jpg","ab") ) == NULL )
        {
                perror("File");
                close(listensd);
                exit(1);
        }
        while( 1 )
        {
                int   rn ;
                int   sin_len = sizeof(client);
                if( (connectsd = accept(listensd,(struct sockaddr *)&client,&sin_len)) < 0 )
                {
                        perror("accept");
                        continue;
                }
                while( 1 )
                {
                        rn = read(connectsd,buf,MAX_LEN);
                        if(rn == 0)
                                break;
                        fwrite(buf,1,rn,fp);
                }
                close(connectsd);
                fclose(fp);
        }
        close(listensd);
        return   0;
}

客户端


/* client端代码:向server端传输一个图片1.jpg */

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include   <stdlib.h>
#include   <unistd.h>
#include   <arpa/inet.h>
#include   <netdb.h>
#define RECVBUFSIZE 1024

int main(int argc,char *argv[]){
        int sockfd,len;
        char buffer[RECVBUFSIZE];
        struct sockaddr_in server_addr;
        struct hostent *host;
        int portnumber,nbytes;
        FILE *fq;

        if(argc != 3){
                fprintf(stderr, "Usage:%s hostname portnumber\a\n",argv[0]);
                exit(1);
        }

        if((portnumber=atoi(argv[2])) < 0){
                fprintf(stderr, "Usage:%s hostname portnumber\a\n",argv[0]);
                exit(1);
        }

        /*客户端程序开始建立sockfd描述符*/
        if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1){
                fprintf(stderr, "Socket Error:%s\a\n",strerror(errno));
                exit(1);
        }

        /*客户端程序填充服务端的资料*/
        bzero(&server_addr,sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(portnumber);
        server_addr.sin_addr.s_addr = inet_addr(argv[1]);

        /*客户端程序发起连接请求*/
        if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr)) == -1){
                fprintf(stderr, "Connect Error:%s\a\n",strerror(errno));
                exit(1);
        }

        /*连接成功,接收数据*/
        if( ( fq = fopen("tempdata.jpg","rb") ) == NULL )

        {

                perror("File open");

                close(sockfd);

                exit(1);

        }

        bzero(buffer,sizeof(buffer));

        while( !feof(fq) )

        {

                len = fread(buffer,1,RECVBUFSIZE,fq);

                if( len != write(sockfd,buffer,len) )

                {

                        perror("write");

                        break;

               }

        }

        close(sockfd);

        fclose(fq);

        if(nbytes > 0) printf("I have received:%s\n",buffer);

        /*结束通信*/
        close(sockfd);
        exit(0);
}

—————————————————————————

参考的代码
客户端

/* client端代码:向server端传输一个图片1.jpg */

#include   <stdio.h>

#include   <sys/socket.h>

#include   <stdlib.h>

#include   <sys/types.h>

#include   <string.h>

#include   <unistd.h>

#include   <netinet/in.h>

#include   <arpa/inet.h>

#include   <netdb.h>

#define   SER_PORT      1900

#define   MAX_LEN      256

int main(int argc,char **argv)

{

        int     sd,rn;

        struct sockaddr_in   client,server;

        char    buf[MAX_LEN];

        FILE    *fq;

        int     len,opt = 1;

        if( ( sd = socket(AF_INET,SOCK_STREAM,0)) == -1 )

        {

                perror("socket");

                exit(1);

        }

        bzero(&server,sizeof(server));

        server.sin_family = AF_INET;

        server.sin_port = htons(SER_PORT);

        server.sin_addr.s_addr = inet_addr("192.168.150.37");

         setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));

         if( connect(sd,(struct sockaddr *)&server,sizeof(server)) < 0 )

        {

                perror("Connect");

                close(sd);

                exit(1);

        }

        if( ( fq = fopen("1.jpg","rb") ) == NULL )

        {

                perror("File open");

                close(sd);

                exit(1);

        }

        bzero(buf,sizeof(buf));

        while( !feof(fq) )

        {

                len = fread(buf,1,MAX_LEN,fq);

                if( len != write(sd,buf,len) )

                {

                        perror("write");

                        break;

               }

        }

        close(sd);

        fclose(fq);

        return 0;

}   

服务器端

/* server端代码:接受Client端发送过来的一个图片 */

#include   <sys/socket.h>

#include   <sys/types.h>

#include   <stdlib.h>

#include   <stdio.h>

#include   <string.h>

#include   <unistd.h>

#include   <error.h>

#include   <netinet/in.h>

#include   <arpa/inet.h>

#define   SER_PORT      1900

#define   MAX_LEN       256


int main(int argc,char **argv)

{

        int     listensd,connectsd;

        struct sockaddr_in   server;

        struct sockaddr_in   client;

        char    buf[MAX_LEN] = "\0";

        FILE    *fp;

        int     opt = 1;

        if( ( listensd = socket(AF_INET,SOCK_STREAM,0) ) == -1 )

        {

                perror("socket");

                exit(1);

        }

        setsockopt(listensd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));

         bzero(&server,sizeof(server));

        server.sin_family = AF_INET;

        server.sin_port = htons(SER_PORT);

        server.sin_addr.s_addr = htonl(INADDR_ANY);

         if( bind(listensd,(struct sockaddr *)&server,sizeof(server)) < 0)

        {

                perror("Bind");

                close(listensd);

                exit(1);

        }

         if( listen(listensd,5) == -1 )

        {

                perror("listen");

                close(listensd);

                exit(1);

        }

         if( ( fp = fopen("new1.jpg","ab") ) == NULL )

        {

                perror("File");

                close(listensd);

                exit(1);

        }

        while( 1 )         

        {

                int   rn ;

                int   sin_len = sizeof(client);

                if( (connectsd = accept(listensd,(struct sockaddr *)&client,&sin_len)) < 0 )

                {

                        perror("accept");

                        continue;

                }

                while( 1 )

                {

                        rn = read(connectsd,buf,MAX_LEN);

                        if(rn == 0)

                                break;

                        fwrite(buf,1,rn,fp);

                }

                close(connectsd);

                fclose(fp);

        }

        close(listensd);

        return   0;

}   

——————————————————————

还有一个参考代码的版本,是将图片放到数据库里面的
服务器端

#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/errno.h>
#include <mysql.h>
#include <unistd.h>

void finish_with_error(MYSQL *con)
{
  fprintf(stderr, "%s\n", mysql_error(con));
  mysql_close(con);
  exit(1);        
}

int PtTcpRcv(int sockfd, char *buffer, int length)
{
      int  len=0;
      int  totalcnt;
      totalcnt = 0;

      while(totalcnt < length) {
        len = read(sockfd, buffer + totalcnt, length - totalcnt);
        if (len < 0) {
          if ((errno == EINTR)||(errno == EAGAIN)) {
            len = 0;
            break;
          }
          else
            {
              return(-1);
            }
        }
        else if (len == 0)
        {
          break;
        }

        totalcnt = totalcnt + len;

      }

   return(totalcnt);
}

int main()
{
    int sfp,nfp,size;
    struct sockaddr_in s_add,c_add;
    socklen_t sin_size;
    unsigned short portnum=12306;
    char rcvbuf[30960];
    printf("Hello,welcome to my server !\n");
    sfp = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sfp)
    {
        printf("socket fail ! \n");
        return -1;
    }
    printf("socket ok !\n");

    bzero(&s_add,sizeof(struct sockaddr_in));
    s_add.sin_family=AF_INET;
    s_add.sin_addr.s_addr=htonl(INADDR_ANY);
    s_add.sin_port=htons(portnum);

    if(-1 == bind(sfp,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
    {
        printf("bind fail !\n");
        return -1;
    }
    printf("bind ok !\r\n");

    if(-1 == listen(sfp,5))
    {
        printf("listen fail !\n");
        return -1;
    }
    printf("listen ok\n");

    while(1)
    {
    sin_size = sizeof(struct sockaddr_in);

    nfp = accept(sfp, (struct sockaddr *)(&c_add), &sin_size);
    if(-1 == nfp)
    {
        printf("accept fail !\n");
        return -1;
    }
    printf("accept ok!\r\nServer start get connect from %#x : %d\n",ntohl(c_add.sin_addr.s_addr),ntohs(c_add.sin_port));
    size = 0;
    memset(rcvbuf, 0x00, sizeof(rcvbuf));
    size = PtTcpRcv(nfp, rcvbuf , sizeof(rcvbuf));
    if(-1 == size)
    {
        printf("write fail!\n");
        return -1;
    }
    printf("write ok!\n");
    printf("%d \n [%s] \n",size, rcvbuf);
    MYSQL *con = mysql_init(NULL);

  if (con == NULL)
  {
      fprintf(stderr, "mysql_init() failed\n");
      exit(1);
  }  

  if (mysql_real_connect(con, "localhost", "root", "1qazxsw2#", 
          "card", 0, NULL, 0) == NULL) 
  {
      finish_with_error(con);
  }   

  char chunk[2*size+1];
  mysql_real_escape_string(con, chunk, rcvbuf, size);

  char *st = "INSERT INTO card_pack(code_img) VALUES( '%s')";
  size_t st_len = strlen(st);

  char query[st_len + 2*size+1]; 
  int len = snprintf(query, st_len + 2*size+1, st, chunk);

  if (mysql_real_query(con, query, len))
  {
      finish_with_error(con);
  }

  mysql_close(con);
    close(nfp);
    }


    close(sfp);
    return 0;
}

客户端

#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#include <string.h>
#include <unistd.h>
#include <sys/errno.h>
#include <stdarg.h>

#include <time.h>
#include <sys/stat.h>

int PtTcpSnd(int sockfd, char *buffer, int length)
{
  int  len;
  int  totalcnt;     
  totalcnt = 0;

  printf("Now Send Socket[%d]...",sockfd);
  while(totalcnt < length) 
  {
    len = write(sockfd, buffer + totalcnt, length - totalcnt);
    printf("Send Socket len[%d]",len);
    if (len < 0) 
    {
      if (errno == EINTR) 
      {
        len = 0;
        break;
      }
      else
        return(-1);
    }
    else if (len == 0)
      break;

    totalcnt = totalcnt + len;
  }

   return(totalcnt);
}


int main()
{
int cfd;

struct sockaddr_in s_add;
unsigned short portnum=12306; 
printf("Hello,welcome to client !\r\n");

cfd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == cfd)
{
    printf("socket fail ! \r\n");
    return -1;
}
printf("socket ok !\r\n");

bzero(&s_add,sizeof(struct sockaddr_in));
s_add.sin_family=AF_INET;
s_add.sin_addr.s_addr= inet_addr("127.0.0.1");
s_add.sin_port=htons(portnum);


if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
{
    printf("connect fail !\r\n");
    return -1;
}
printf("connect ok !\r\n");

FILE *fp = fopen("qr.jpg", "rb");

  if (fp == NULL) 
  {
      fprintf(stderr, "cannot open image file\n");    
      exit(1);
  }

  fseek(fp, 0, SEEK_END);

  if (ferror(fp)) {

      fprintf(stderr, "fseek() failed\n");
      int r = fclose(fp);

      if (r == EOF) {
          fprintf(stderr, "cannot close file handler\n");          
      }    

      exit(1);
  }  

  int flen = ftell(fp);

  if (flen == -1) {

      perror("error occurred");
      int r = fclose(fp);

      if (r == EOF) {
          fprintf(stderr, "cannot close file handler\n");
      }

      exit(1);      
  }

  fseek(fp, 0, SEEK_SET);

  if (ferror(fp)) {

      fprintf(stderr, "fseek() failed\n");
      int r = fclose(fp);

      if (r == EOF) {
          fprintf(stderr, "cannot close file handler\n");
      }    

      exit(1);
  }

  char data[flen+1];

  int size = fread(data, 1, flen, fp);

  if (ferror(fp)) {

      fprintf(stderr, "fread() failed\n");
      int r = fclose(fp);

      if (r == EOF) {
          fprintf(stderr, "cannot close file handler\n");
      }

      exit(1);      
  }

  int r = fclose(fp);

  if (r == EOF) {
      fprintf(stderr, "cannot close file handler\n");
  } 
  printf("%d\n [%#x]\n", size, data);
if (PtTcpSnd(cfd, data, size) < 0)  { 
printf("sending on stream socket");   
close(cfd);   
exit(0);   
}  

close(cfd);
return 0;
}

————————————————————-

自己写的TCP通信的代码
客户端

/**********客户端程序************/

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define RECVBUFSIZE 1024

int main(int argc,char *argv[]){
        int sockfd;
        char buffer[RECVBUFSIZE];
        struct sockaddr_in server_addr;
        struct hostent *host;
        int portnumber,nbytes;

        if(argc != 3){
                fprintf(stderr, "Usage:%s hostname portnumber\a\n",argv[0]);
                exit(1);
        }

        if((portnumber=atoi(argv[2])) < 0){
                fprintf(stderr, "Usage:%s hostname portnumber\a\n",argv[0]);
                exit(1);
        }

        /*客户端程序开始建立sockfd描述符*/
        if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1){
                fprintf(stderr, "Socket Error:%s\a\n",strerror(errno));
                exit(1);
        }

        /*客户端程序填充服务端的资料*/
        bzero(&server_addr,sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(portnumber);
        server_addr.sin_addr.s_addr = inet_addr(argv[1]);

        /*客户端程序发起连接请求*/
        if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr)) == -1){
                fprintf(stderr, "Connect Error:%s\a\n",strerror(errno));
                exit(1);
        }

        /*连接成功,接收数据*/
        if((nbytes = recv(sockfd,buffer,RECVBUFSIZE,0)) == -1){
                fprintf(stderr, "Read Error:%s\a\n",strerror(errno));
                exit(1);
        }
        buffer[nbytes] = '\0';

        if(nbytes > 0) printf("I have received:%s\n",buffer);

        /*结束通信*/
        close(sockfd);
        exit(0);
}

服务器端


/**************服务器端程序***************/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <time.h>

int sockfd;

void do_service(fd)
{
    long t = time(0);
    char *s = ctime(&t);
    write(fd,s,strlen(s));
}
void out_client(struct sockaddr_in clientaddr)
{
    char buffer[16];
    inet_ntop(AF_INET,&clientaddr.sin_addr.s_addr,buffer,sizeof(clientaddr));
    unsigned short port = ntohs(clientaddr.sin_port);
    printf("client ip:%s (%d)\n",buffer,port);
}


int main(int argc,char *argv[])
{
    if(argc < 2)
    {
        fprintf(stderr,"usage: %s port\n",argv[0]);
        exit(1);
    }

    /*create socket*/
    sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        fprintf(stderr,"socket: %s\n",strerror(errno));
        exit(1);
    }

    /*set ip and port*/
    struct sockaddr_in addr;
    memset(&addr,0,sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[1]));
    addr.sin_addr.s_addr = INADDR_ANY;

    /*bind ip and port*/
    int len = sizeof(addr);
    if(bind(sockfd,(struct sockaddr*)&addr,len) < 0)
    {
        fprintf(stderr,"bind: %s\n",strerror(errno));
        exit(1);
    }

    /*begin to listen*/
    if(listen(sockfd,10) < 0)
    {
        fprintf(stderr,"listen: %s\n",strerror(errno));
        exit(1);
    }

    while(1)
    {
        struct sockaddr_in clientaddr;
        int c_len = sizeof(clientaddr);
        int fd = accept(sockfd,(struct sockaddr*)&clientaddr,&c_len);
        if(fd < 0)
        {
            fprintf(stderr,"accept: %s\n",strerror(errno));
            continue;
        }
        out_client(clientaddr);
        do_service(fd);
        close(fd);

    }
    return 0;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页