c++ socket通信完整
#include <pcl\io\pcd_io.h>
#include <pcl\visualization\pcl_visualizer.h>
#include <iostream>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/common/io.h>
#include <vector>
#include <pcl/common/impl/io.hpp>
#include <iostream>
#include <Eigen/Dense>
#include <pcl/point_types.h>
#include <vtkAutoInit.h>
#include <vtkRenderWindow.h>
#include <vtkPNGReader.h>
#include <vtkImageData.h>
#include <vtkLogoRepresentation.h>
#include <vtkLogoWidget.h>
#include <vtkAxesActor.h>
#include <vtkOrientationMarkerWidget.h>
#include <vtkScalarBarWidget.h>
#include <vtkScalarBarActor.h>
#include <vtkScalarBarRepresentation.h>
#include <vtkColorTransferFunction.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/point_cloud_color_handlers.h>
#include<winsock.h>
#pragma comment(lib,"ws2_32.lib")
#include<string>
#include<windows.h>
using namespace std;
typedef pcl::PointXYZ PointT;
typedef pcl::PointCloud<PointT> PointCloudT;
void
main(int argc, char** argv)
{
string send_buf = "cbcdfg";
cout << "send_info \n" << send_buf << endl;
Sleep(5);
// socket 通信部分 -----------------------------
//定义长度变量
int send_len = 0;
int recv_len = 0;
//定义发送缓冲区和接受缓冲区
//char send_buf[] = "四个点的信息!!!";
char recv_buf[100];
//string recv_buf;
//定义服务端套接字,接受请求套接字
SOCKET s_server;
//服务端地址客户端地址
SOCKADDR_IN server_addr;
initialization();
//填充服务端信息
server_addr.sin_family = AF_INET;
server_addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.113");
server_addr.sin_port = htons(7777);
//创建套接字
s_server = socket(AF_INET, SOCK_STREAM, 0);
if (connect(s_server, (SOCKADDR*)&server_addr, sizeof(SOCKADDR)) == SOCKET_ERROR) {
cout << "服务器连接失败!" << endl;
WSACleanup();
}
else {
cout << "服务器连接成功!" << endl;
}
//发送,接收数据
send_len = send(s_server, send_buf.c_str(), send_buf.length(), 0);
if (send_len < 0) {
cout << "发送失败!" << endl;
}
while (1) {
recv_len = recv(s_server, recv_buf, 100, 0);
if (recv_len < 0) {
//cout << "接受失败!" << endl;
//break;
}
else {
cout << "服务端信息:" << recv_buf << endl;
break;
}
}
//关闭套接字
closesocket(s_server);
//释放DLL资源
WSACleanup();
cout << "通信结束!!!" << endl;
// --------end ---------
}
void initialization() {
//初始化套接字库
WORD w_req = MAKEWORD(2, 2);//版本号
WSADATA wsadata;
int err;
err = WSAStartup(w_req, &wsadata);
if (err != 0) {
cout << "初始化套接字库失败!" << endl;
}
else {
cout << "初始化套接字库成功!" << endl;
}
//检测版本号
if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wHighVersion) != 2) {
cout << "套接字库版本号不符!" << endl;
WSACleanup();
}
else {
cout << "套接字库版本正确!" << endl;
}
//填充服务端地址信息
}