资源简介
socket(网络套接字)传输图片
代码片段和文件信息
#include
#include
#include
#include
#pragma comment(lib“ws2_32.lib“)
using namespace std;
struct Data
{
char message[2000];
int rest;
}data;
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
int result;
SOCKET sConnect;
struct sockaddr_in saServer;
ifstream sendPicture(“2.bmp“ ios::in | ios::binary);
/************************* 构建传输文件信息 *************************/
sendPicture.seekg(0 std::ios_base::end);
int pictureLengh = sendPicture.tellg();
sendPicture.seekg(0 std::ios_base::beg);
/************************* 构建服务器地址信息 *************************/
saServer.sin_family = AF_INET; //地址家族
saServer.sin_port = htons(9210); //服务器端口
saServer.sin_addr.S_un.S_addr = inet_addr(“127.0.0.1“);//服务器地址
/************************* WinSock初始化 *************************/
wVersionRequested = MAKEWORD(2 2);
result = WSAStartup(wVersionRequested &wsaData);
if (result != 0)
{
printf(“WSAStartup() failed!\n“);
return 0;
}
//确认WinSock DLL支持版本2.2
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
WSACleanup();
printf(“Invalid WinSock version!\n“);
return 0;
}
/************************* 创建Socket *************************/
sConnect = socket(AF_INET SOCK_STREAM 0);
if (sConnect == INVALID_SOCKET)
{
WSACleanup();
cout << “socket() faild!“ << endl;
return 0;
}
/************************* 连接服务器 *************************/
result = connect(sConnect (struct sockaddr *)&saServer sizeof(saServer));
if (result == SOCKET_ERROR)
{
printf(“connect() failed!\n“);
closesocket(sConnect); //关闭套接字
WSACleanup();
return 0;
}
/************************* 传输 *************************/
cout << “连接服务器成功“ << endl;
int num = 1;
while (1)
{
sendPicture.read(data.message 1024);
pictureLengh -= 1024;
if (pictureLengh <= 0)
data.rest = 0;
else
data.rest = 1;
result = send(sConnect (char *)&data sizeof(struct Data) 0);
cout << “发送第“ << num++ << “信息“ << endl;
if (data.rest == 0){
cout << “over“ << endl;
break;
}
if (result == SOCKET_ERROR)
{
printf(“send() failed!\n“);
}
}
closesocket(sConnect);
WSACleanup();
return 0;
}
/************************发送信息****************************/
//strcpy_s(data.name “QQ小业“);
//cout << “please send a message:“ << endl << “QQ小业:“;
//cin >> data.message;
//if (strcmp(data.message “886“) == 0) break;
//result = send(sConnect (char *)&data sizeof(struct Data) 0);
//if (result == SOCKET_ERROR)
//{
// printf(“send() failed!\n“);
//}
//
///************************接收信息****************************/
//result = recv(sConnect (char *)&data sizeof(struct Data) 0);
//if (result == SOCKET_ERROR)
//{
// printf(“recv() failed!\n“);
// return 0;
//}
//if (result == 0) //客户端已经关闭连接
//{
// printf(“Client has closed the connection\n“);
// break;
//}
//cout << “
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 3930 2017-08-25 17:21 server.cpp
文件 3198 2017-08-25 17:21 client.cpp
评论
共有 条评论