我正在使用客户端 - 服务器通信来传输图像,当我从我的相机捕获图像时,它是一个rgb数组,我使用imencode编码为jpeg格式。
vector<unsigned char>buff;
imencode(".jpg",img,buff);
如何将其发送到客户端并将该数据保存到.jpg文件?
简单的服务器端 -
#include <stdio.h>
#include <string.h>
#include <sstream>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<fstream>
#include<errno.h>
int main(int argc , char **argv)
{
int socket_desc , new_socket , read_size , c , buffer = 0 , n = 0;
struct sockaddr_in server , client ;
socket_desc = socket(AF_INET , SOCK_STREAM , 0) ;
server.sin_family = AF_INET ;
server.sin_addr.s_addr = INADDR_ANY ;
server.sin_port = htons(8000) ;
if(bind(socket_desc , (struct sockaddr *)&server , sizeof(server))<0)
{
puts("bind failed") ;
return 1;
}
puts("Binding was done now waiting for an incoming client") ;
listen(socket_desc , 3) ;
c = sizeof(struct sockaddr_in);
if((new_socket = accept(socket_desc , (struct sockaddr *)&client ,
(socklen_t*)&c)))
{
puts("accepted your connection request") ;
}
fflush(stdout) ;
if(new_socket<0)
{
puts("Looks like connection with cliento was not a success");
}
image = cv::imread("a.jpg") ;
std::vector<uchar> buff ;
cv::imencode(".jpg" , image , buff) ;
// Sending a normal mssg instead of jpeg data
char send[] = {'a' , 'b' , 'c'} ;
n = write(new_socket , send , 10) ;
if(n<0)
{
puts("Looks like there was an error while writing to client") ;
}
close(socket_desc);
return 0 ;
}
客户端 -
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<sys/ioctl.h>
#include<unistd.h>
#include<iostream>
#include<fstream>
#include<errno.h>
int main(int argc , char *argv[])
{
// variable initialization
int socket_desc , n = 0;
struct sockaddr_in server;
char *parray;
char buffer[256];
// creating a socket
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1) {
printf("Socket couldn't be created");
}
// do servo initialization
memset(&server,0,sizeof(server));
server.sin_addr.s_addr = inet_addr("192.168.137.3");
server.sin_family = AF_INET;
server.sin_port = htons( 8000 );
// Finally connect to servo
if (connect(socket_desc , (struct sockaddr *)&server , sizeof(server)) < 0)
{
cout<<strerror(errno);
close(socket_desc);
puts("There was a connection error with server");
return 1;
}
puts("Successfully got connected with server") ;
n = read(socket_desc,buffer,255);
if (n < 0) {
perror("There was an error reading from server");
exit(1);
}
printf("Here is the message from server: %s\n",buffer);
close(socket_desc) ;
return 0 ;
}
当客户端发送请求时,我需要做的就是捕获RGB格式的图像然后将其编码为jpeg格式,将其发送到客户端,然后在客户端读取它并将其保存为.jpg文件。