Linux(客户端)和Windows(服务端)下socket通信实例:
(1)首先是Windows做客户端,Linux做服务端的程序
Windows Client端
1 #include <stdio.h> 2 #include <Windows.h> 3 #pragma comment(lib, "ws2_32.lib") 4 #define Port 5000 5 #define IP_ADDRESS "192.168.1.30" //服务器地址 6 int main() // argc是命令行总的参数个数 7 { 8 WSADATA s; // 用来储存调用AfxSocketInit全局函数返回的Windows Sockets初始化信息 9 SOCKET ClientSocket; 10 struct sockaddr_in ClientAddr; // 一个sockaddr_in型的结构体对象 11 int ret = 0; 12 char SendBuffer[MAX_PATH]; // Windows的MAX_PATH默认是260 13 // 初始化Windows Socket 14 // WSAStartup函数对Winsock服务的初始化 15 if (WSAStartup(MAKEWORD(2, 2), &s) != 0) // 通过连接两个给定的无符号参数,首个参数为低字节 16 { 17 printf("Init Windows Socket Failed! Error: %d ", GetLastError()); 18 getchar(); 19 return -1; 20 } 21 while (1) 22 { 23 // 创建一个套接口 24 // 如果这样一个套接口用connect()与一个指定端口连接 25 // 则可用send()和recv()与该端口进行数据报的发送与接收 26 // 当会话结束后,调用closesocket() 27 ClientSocket = socket(AF_INET, // 只支持ARPA Internet地址格式 28 SOCK_STREAM, // 新套接口的类型描述 29 IPPROTO_TCP); // 套接口所用的协议 30 if (ClientSocket == INVALID_SOCKET) 31 { 32 printf("Create Socket Failed! Error: %d ", GetLastError()); 33 getchar(); 34 return -1; 35 } 36 ClientAddr.sin_family = AF_INET; 37 ClientAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS); // 定义IP地址 38 ClientAddr.sin_port = htons(Port); // 将主机的无符号短整形数转换成网络字节顺序 39 memset(ClientAddr.sin_zero, 0X00, 8); // 函数通常为新申请的内存做初始化工作 40 // 连接Socket 41 ret = connect(ClientSocket, 42 (struct sockaddr*)&ClientAddr, 43 sizeof(ClientAddr)); 44 if (ret == SOCKET_ERROR) 45 { 46 printf("Socket Connect Failed! Error:%d ", GetLastError()); 47 getchar(); 48 return -1; 49 } 50 else 51 { 52 printf("Socket Connect Succeed!"); 53 } 54 printf("Input Data: "); 55 while (1) 56 { 57 scanf("%s", &SendBuffer); 58 // 发送数据至服务器 59 ret = send(ClientSocket, 60 SendBuffer, 61 (int)strlen(SendBuffer), // 返回发送缓冲区数据长度 62 0); 63 if (ret == SOCKET_ERROR) 64 { 65 printf("Send Information Failed! Error:%d ", GetLastError()); 66 getchar(); 67 break; 68 } 69 break; 70 } 71 // 关闭socket 72 closesocket(ClientSocket); 73 if (SendBuffer[0] == 'q') // 设定输入第一个字符为q时退出 74 { 75 printf("Quit! "); 76 break; 77 } 78 } 79 WSACleanup(); 80 getchar(); 81 system("pause"); 82 return 0; 83 } 84 85 Linux server端 86 87 #include <stdio.h> 88 #include <sys/socket.h> 89 #include <sys/types.h> /* See NOTES */ 90 #include <sys/socket.h> 91 #include <arpa/inet.h> 92 #include <string.h> 93 #include<unistd.h> 94 #include <cstdlib> 95 #define SERVER_PORT 5000 96 #define LENGTH_OF_LISTEN_QUEUE 20 97 #define BUFFER_SIZE 10 98 int main() // (int argc, char* argv[]) 99 { 100 struct sockaddr_in server_addr; 101 int server_socket; 102 int opt = 1; 103 bzero(&server_addr, sizeof(server_addr)); // 置字节字符串前n个字节为0,包括' ' 104 server_addr.sin_family = AF_INET; 105 server_addr.sin_addr.s_addr = htons(INADDR_ANY); // 转小端,INADDR_ANY就是指定地址为0.0.0.0的地址 106 server_addr.sin_port = htons(SERVER_PORT); 107 // 创建一个Socket 108 server_socket = socket(PF_INET, SOCK_STREAM, 0); 109 if (server_socket < 0) 110 { 111 printf("Create Socket Failed! "); 112 exit(1); 113 } 114 // bind a socket 115 setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); 116 if(bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr))) 117 { 118 printf("Server Bind Port: %d Failed! ", SERVER_PORT); 119 exit(1); 120 } 121 // 监听Socket 122 if (listen(server_socket, LENGTH_OF_LISTEN_QUEUE)) 123 { 124 printf("Server Listen Failed! "); 125 exit(1); 126 } 127 while(1) 128 { 129 struct sockaddr_in client_addr; 130 int client_socket; 131 socklen_t length; 132 char Buffer[BUFFER_SIZE]; 133 // 连接客户端Socket 134 length = sizeof(client_addr); 135 client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length); 136 if (client_socket < 0) 137 { 138 printf("Server Accept Failed! "); 139 break; 140 } 141 // 从客户端接收数据 142 while(1) 143 { 144 bzero(Buffer, BUFFER_SIZE); 145 length = recv(client_socket, Buffer, BUFFER_SIZE, 0); 146 if (length < 0) 147 { 148 printf("Server Recieve Data Failed! "); 149 break; 150 } 151 if ('q' == Buffer[0]) 152 { 153 printf("Quit! "); 154 break; 155 } 156 printf("%s ", Buffer); 157 break; 158 } 159 close(client_socket); 160 } 161 close(server_socket); 162 return 0; 163 }
(2)Windows做服务端,Linux做客户端实例 传输视频
windows端:
1 #include <stdio.h> 2 #include <string> 3 #include <iostream> 4 #include <Winsock2.h> 5 #include <opencv2/opencv.hpp> 6 #include <vector> 7 #include "globalsetting.h" 8 #pragma comment(lib,"ws2_32.lib") 9 10 11 12 /** 13 * OpenCV video streaming over TCP/IP 14 * Client: Receives video from server and display it 15 * Created by Wu yongcong 2017-8-24 16 */ 17 18 using namespace cv; 19 using namespace std; 20 21 22 int main() 23 { 24 25 //-------------------------------------------------------- 26 //networking stuff: socket , connect 27 //-------------------------------------------------------- 28 WSADATA wsaData; 29 SOCKET sockClient;//客户端Socket 30 SOCKADDR_IN addrServer;//服务端地址 31 WSAStartup(MAKEWORD(2, 2), &wsaData); 32 33 //新建客户端socket 34 sockClient = socket(AF_INET, SOCK_STREAM, 0); 35 36 //定义要连接的服务端地址 37 addrServer.sin_addr.S_un.S_addr = inet_addr(SOCKET_IP); //服务端IP 38 addrServer.sin_family = AF_INET; 39 addrServer.sin_port = htons(SOCKET_PORT);//服务端连接端口 40 41 //连接到服务端 42 connect(sockClient, (SOCKADDR*)&addrServer, sizeof(SOCKADDR)); 43 44 //---------------------------------------------------------- 45 //OpenCV Code 46 //---------------------------------------------------------- 47 48 Mat img; 49 img = Mat::zeros(480 , 640, CV_8UC3);//CV_8UC3代表是三通道 50 int imgSize = img.total() * img.elemSize(); 51 uchar *iptr = img.data; 52 int bytes = 0; 53 int key; 54 55 //make img continuos 56 57 if ( ! img.isContinuous() ) { 58 img = img.clone(); 59 } 60 61 std::cout << "Image Size:" << imgSize << std::endl; 62 namedWindow("CV Video Client",1); 63 while (key != 'q') { 64 if ((bytes = recv(sockClient, (char *)iptr, imgSize , MSG_WAITALL)) == -1) { 65 std::cerr << "recv failed, received bytes = " << bytes << std::endl; 66 } 67 cv::imshow("CV Video Client", img); 68 if (key = cv::waitKey(10) >= 0) break; 69 } 70 closesocket(sockClient); 71 72 WSACleanup(); 73 74 return 0; 75 } 76 77
linux端:
编译命令:
g++ `pkg-config --cflags opencv` -o server -pthread socketServer.cpp `pkg-config --libs opencv`
1 #include "opencv2/opencv.hpp" 2 #include <iostream> 3 #include <sys/socket.h> 4 #include <arpa/inet.h> 5 #include <sys/ioctl.h> 6 #include <net/if.h> 7 #include <unistd.h> 8 #include <string.h> 9 #include <stdio.h> 10 #include <stdlib.h> 11 #include <pthread.h> 12 #include "socketSetting.h" 13 /* 14 * Created by Wu yongcong 2017-8-25 15 * 16 * socket transfer video server 17 * 18 */ 19 using namespace cv; 20 using namespace std; 21 void *display(void *); 22 VideoCapture cap(CAMMER_PORT); // open the default camera 23 int main(int argc, char** argv) 24 { 25 //-------------------------------------------------------- 26 //networking stuff: socket, bind, listen 27 //-------------------------------------------------------- 28 int localSocket, 29 remoteSocket, 30 port = IP_PORT; 31 struct sockaddr_in localAddr, 32 remoteAddr; 33 pthread_t thread_id; 34 int addrLen = sizeof(struct sockaddr_in); 35 localSocket = socket(AF_INET , SOCK_STREAM , 0); 36 if (localSocket == -1){ 37 perror("socket() call failed!!"); 38 } 39 localAddr.sin_family = AF_INET; 40 localAddr.sin_addr.s_addr = INADDR_ANY; 41 localAddr.sin_port = htons( port ); 42 if( bind(localSocket,(struct sockaddr *)&localAddr , sizeof(localAddr)) < 0) { 43 perror("Can't bind() socket"); 44 exit(1); 45 } 46 //Listening 47 listen(localSocket , 3); 48 std::cout << "Waiting for connections... " 49 << "Server Port:" << port << std::endl; 50 //accept connection from an incoming client 51 while(1){ 52 remoteSocket = accept(localSocket, (struct sockaddr *)&remoteAddr, (socklen_t*)&addrLen); 53 if (remoteSocket < 0) { 54 perror("accept failed!"); 55 exit(1); 56 } 57 std::cout << "Connection accepted" << std::endl; 58 pthread_create(&thread_id,NULL,display,&remoteSocket); 59 //pthread_join(thread_id,NULL); 60 } 61 //pthread_join(thread_id,NULL); 62 //close(remoteSocket); 63 return 0; 64 } 65 void *display(void *ptr){ 66 int socket = *(int *)ptr; 67 //OpenCV Code 68 //---------------------------------------------------------- 69 Mat img, imgGray,imgColor; 70 img = Mat::zeros(480,640,CV_8UC3); 71 //make it continuous 72 if (!img.isContinuous()) { 73 img = img.clone(); 74 } 75 // int imgSize = img.total() * img.elemSize(); 76 int imgSize = img.total() * img.channels(); 77 int bytes = 0; 78 int key; 79 //make img continuos 80 if ( !img.isContinuous() ) { 81 img = img.clone(); 82 imgGray = img.clone(); 83 } 84 std::cout << "Image Size:" << imgSize << std::endl; 85 while(1) { 86 /* get a frame from camera */ 87 cap >> img; 88 if (img.empty()) break; 89 //cvtColor(img, imgGray, CV_RGB2GRAY); // color change 90 //send processed image 91 if ((bytes = send(socket, img.data, imgSize, 0)) < 0){ 92 std::cerr << "bytes = " << bytes << std::endl; 93 break; 94 } 95 } 96 }