问题描述
我正在使用套接字编程编写图像文件传输的代码。 在这里,客户端向服务器发送一个请求消息,将某个文件发送给客户端。从客户端收到消息后,服务器正在向客户端发送文本文件。 但现在我需要修改它以接收图像文件而不是文本文件。
这是服务器和客户端代码
//**server**
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <WS2tcpip.h>
#include <string>
#define SIZE 10241
#pragma comment (lib,"ws2_32.lib")
using namespace std;
void send_file(FILE* fp,int clientSocket) {
//int n;
char data[SIZE] = { 0 };
while (fgets(data,SIZE,fp) != NULL) {
if (send(clientSocket,data,sizeof(data),0) == -1) {
perror("[-]Error in sending file.");
exit(1);
}
//bzero(data,SIZE);
//memset((data),'\0',(SIZE)),(void)0);
}
}
void main()
{
// Initialze winsock
WSADATA wsData;
WORD ver = MAKEWORD(2,2);
int wsOk = WSAStartup(ver,&wsData);
if (wsOk != 0)
{
cerr << "Can't Initialize winsock! Quitting" << endl;
return;
}
// Create a socket
SOCKET listening = socket(AF_INET,SOCK_STREAM,0);
if (listening == INVALID_SOCKET)
{
cerr << "Can't create a socket! Quitting" << endl;
return;
}
else
{
printf("socket created \n");
}
// Bind the ip address and port to a socket
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(54000);
hint.sin_addr.S_un.S_addr = INADDR_ANY; // Could also use inet_pton ....
bind(listening,(sockaddr*)&hint,sizeof(hint));
// Tell Winsock the socket is for listening
//listen(listening,SOMAXCONN);
if (listen(listening,SOMAXCONN) == SOCKET_ERROR) {
printf("Listen Failed with error: %ld\n",WSAGetLastError());
}
else {
printf("listening...\n");
}
// Wait for a connection
sockaddr_in client;
int clientSize = sizeof(client);
SOCKET clientSocket = accept(listening,(sockaddr*)&client,&clientSize);
char host[NI_MAXHOST]; // Client's remote name
char service[NI_MAXSERV]; // Service (i.e. port) the client is connect on
ZeroMemory(host,NI_MAXHOST); // same as memset(host,NI_MAXHOST);
ZeroMemory(service,NI_MAXSERV);
if (getnameinfo((sockaddr*)&client,sizeof(client),host,NI_MAXHOST,service,NI_MAXSERV,0) == 0)
{
cout << host << " connected on port " << service << endl;
}
else
{
inet_ntop(AF_INET,&client.sin_addr,NI_MAXHOST);
cout << host << " connected on port " <<
ntohs(client.sin_port) << endl;
}
FILE* fp = fopen("original.txt","r");
// Close listening socket
//closesocket(listening);
if (fp == NULL) {
perror("[-]Error in reading file.");
exit(1);
}
// While loop: accept and echo message back to client
char buf[4096];
//while (true)
//{
ZeroMemory(buf,4096);
// Wait for client to send data
int bytesReceived = recv(clientSocket,buf,4096,0);
if (bytesReceived > 0)
{
printf("Bytes received: %d\n",bytesReceived);
}
if (bytesReceived == SOCKET_ERROR)
{
//cerr << "Error in recv(). Quitting" << endl;
printf("recv Failed: %d\n",WSAGetLastError());
// break;
}
if (bytesReceived == 0)
{
cout << "Client disconnected " << endl;
// break;
}
cout << string(buf,bytesReceived) << endl;
// Echo message back to client
send(clientSocket,bytesReceived + 1,0);
send_file(fp,clientSocket);
printf("[+]File data sent successfully.\n");
printf("[+]Closing the connection.\n");
// Close the socket
closesocket(clientSocket);
//}
// Cleanup winsock
WSACleanup();
//system("pause");
}
//**client**
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <string>
#include <WS2tcpip.h>
#define SIZE 10241
#pragma comment(lib,"ws2_32.lib")
using namespace std;
void write_file(int sock) {
int n;
FILE* fp;
char buffer[SIZE];
fp = fopen("copy.txt","w");
while (1) {
n = recv(sock,buffer,0);
if (n <= 0) {
break;
return;
}
fprintf(fp,"%s",buffer);
//(memset((buffer),(SIZE)));
}
fclose(fp);
return;
}
void main()
{
string ipAddress = "127.0.0.1"; // IP Address of the server
int port = 54000; // Listening port # on the server
// Initialize WinSock
WSAData data;
WORD ver = MAKEWORD(2,2);
int wsResult = WSAStartup(ver,&data);
if (wsResult != 0)
{
cerr << "Can't start Winsock,Err #" << wsResult << endl;
return;
}
// Create socket
SOCKET sock = socket(AF_INET,0);
if (sock == INVALID_SOCKET)
{
cerr << "Can't create socket,Err #" << WSAGetLastError() << endl;
WSACleanup();
return;
}
// Fill in a hint structure
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET,ipAddress.c_str(),&hint.sin_addr);
// Connect to server
int connResult = connect(sock,sizeof(hint));
if (connResult == SOCKET_ERROR)
{
cerr << "Can't connect to server,Err #" << WSAGetLastError() << endl;
closesocket(sock);
WSACleanup();
return;
}
// Do-while loop to send and receive data
//int new_sock;
//struct sockaddr_in new_addr;
//socklen_t addr_size;
//char buffer[SIZE];
//addr_size = sizeof(new_addr);
//new_sock = accept(listen_socket,(struct sockaddr*)&new_addr,&addr_size);
char buf[4096];
string userInput;
do
{
// Prompt the user for some text
cout << "Write Data : ";
getline(cin,userInput);
if (userInput.size() > 0) // Make sure the user has typed in something
{
// Send the text
int sendResult = send(sock,userInput.c_str(),userInput.size() + 1,0);
if (sendResult != SOCKET_ERROR)
{
// Wait for response
ZeroMemory(buf,4096);
int bytesReceived = recv(sock,0);
if (bytesReceived > 0)
{
// Echo response to console
cout << "SERVER : " << string(buf,bytesReceived) << endl;
write_file(sock);
printf("Data received successfully\n");
}
}
}
break;
} while (userInput.size() > 0);
// close down everything
closesocket(sock);
WSACleanup();
}
谢谢。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)