(8)Linux(客户端)和Windows(服务端)下socket通信实例

时间:2021-12-31 14:35:40

Linux(客户端)和Windows(服务端)下socket通信实例:

(1)首先是Windows做客户端,Linux做服务端的程序

Windows   Client端

     #include <stdio.h>
#include <Windows.h>
#pragma comment(lib, "ws2_32.lib")
#define Port 5000
#define IP_ADDRESS "192.168.1.30" //服务器地址
int main() // argc是命令行总的参数个数
{
WSADATA s; // 用来储存调用AfxSocketInit全局函数返回的Windows Sockets初始化信息
SOCKET ClientSocket;
struct sockaddr_in ClientAddr; // 一个sockaddr_in型的结构体对象
int ret = ;
char SendBuffer[MAX_PATH]; // Windows的MAX_PATH默认是260
// 初始化Windows Socket
// WSAStartup函数对Winsock服务的初始化
if (WSAStartup(MAKEWORD(, ), &s) != ) // 通过连接两个给定的无符号参数,首个参数为低字节
{
printf("Init Windows Socket Failed! Error: %d\n", GetLastError());
getchar();
return -;
}
while ()
{
// 创建一个套接口
// 如果这样一个套接口用connect()与一个指定端口连接
// 则可用send()和recv()与该端口进行数据报的发送与接收
// 当会话结束后,调用closesocket()
ClientSocket = socket(AF_INET, // 只支持ARPA Internet地址格式
SOCK_STREAM, // 新套接口的类型描述
IPPROTO_TCP); // 套接口所用的协议
if (ClientSocket == INVALID_SOCKET)
{
printf("Create Socket Failed! Error: %d\n", GetLastError());
getchar();
return -;
}
ClientAddr.sin_family = AF_INET;
ClientAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS); // 定义IP地址
ClientAddr.sin_port = htons(Port); // 将主机的无符号短整形数转换成网络字节顺序
memset(ClientAddr.sin_zero, 0X00, ); // 函数通常为新申请的内存做初始化工作
// 连接Socket
ret = connect(ClientSocket,
(struct sockaddr*)&ClientAddr,
sizeof(ClientAddr));
if (ret == SOCKET_ERROR)
{
printf("Socket Connect Failed! Error:%d\n", GetLastError());
getchar();
return -;
}
else
{
printf("Socket Connect Succeed!");
}
printf("Input Data: ");
while ()
{
scanf("%s", &SendBuffer);
// 发送数据至服务器
ret = send(ClientSocket,
SendBuffer,
(int)strlen(SendBuffer), // 返回发送缓冲区数据长度
);
if (ret == SOCKET_ERROR)
{
printf("Send Information Failed! Error:%d\n", GetLastError());
getchar();
break;
}
break;
}
// 关闭socket
closesocket(ClientSocket);
if (SendBuffer[] == 'q') // 设定输入第一个字符为q时退出
{
printf("Quit!\n");
break;
}
}
WSACleanup();
getchar();
system("pause");
return ;
} Linux server端 #include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include<unistd.h>
#include <cstdlib>
#define SERVER_PORT 5000
#define LENGTH_OF_LISTEN_QUEUE 20
#define BUFFER_SIZE 10
int main() // (int argc, char* argv[])
{
struct sockaddr_in server_addr;
int server_socket;
int opt = ;
bzero(&server_addr, sizeof(server_addr)); // 置字节字符串前n个字节为0,包括'\0'
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY); // 转小端,INADDR_ANY就是指定地址为0.0.0.0的地址
server_addr.sin_port = htons(SERVER_PORT);
// 创建一个Socket
server_socket = socket(PF_INET, SOCK_STREAM, );
if (server_socket < )
{
printf("Create Socket Failed!\n");
exit();
}
// bind a socket
setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if(bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)))
{
printf("Server Bind Port: %d Failed!\n", SERVER_PORT);
exit();
}
// 监听Socket
if (listen(server_socket, LENGTH_OF_LISTEN_QUEUE))
{
printf("Server Listen Failed!\n");
exit();
}
while()
{
struct sockaddr_in client_addr;
int client_socket;
socklen_t length;
char Buffer[BUFFER_SIZE];
// 连接客户端Socket
length = sizeof(client_addr);
client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &length);
if (client_socket < )
{
printf("Server Accept Failed!\n");
break;
}
// 从客户端接收数据
while()
{
bzero(Buffer, BUFFER_SIZE);
length = recv(client_socket, Buffer, BUFFER_SIZE, );
if (length < )
{
printf("Server Recieve Data Failed!\n");
break;
}
if ('q' == Buffer[])
{
printf("Quit!\n");
break;
}
printf("%s\n", Buffer);
break;
}
close(client_socket);
}
close(server_socket);
return ;
}

(2)Windows做服务端,Linux做客户端实例  传输视频

windows端:

 #include <stdio.h>
#include <string>
#include <iostream>
#include <Winsock2.h>
#include <opencv2/opencv.hpp>
#include <vector>
#include "globalsetting.h"
#pragma comment(lib,"ws2_32.lib") /**
* OpenCV video streaming over TCP/IP
* Client: Receives video from server and display it
* Created by Wu yongcong 2017-8-24
*/ using namespace cv;
using namespace std; int main()
{ //--------------------------------------------------------
//networking stuff: socket , connect
//--------------------------------------------------------
WSADATA wsaData;
SOCKET sockClient;//客户端Socket
SOCKADDR_IN addrServer;//服务端地址
WSAStartup(MAKEWORD(, ), &wsaData); //新建客户端socket
sockClient = socket(AF_INET, SOCK_STREAM, ); //定义要连接的服务端地址
addrServer.sin_addr.S_un.S_addr = inet_addr(SOCKET_IP); //服务端IP
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(SOCKET_PORT);//服务端连接端口 //连接到服务端
connect(sockClient, (SOCKADDR*)&addrServer, sizeof(SOCKADDR)); //----------------------------------------------------------
//OpenCV Code
//---------------------------------------------------------- Mat img;
img = Mat::zeros( , , CV_8UC3);//CV_8UC3代表是三通道
int imgSize = img.total() * img.elemSize();
uchar *iptr = img.data;
int bytes = ;
int key; //make img continuos if ( ! img.isContinuous() ) {
img = img.clone();
} std::cout << "Image Size:" << imgSize << std::endl;
namedWindow("CV Video Client",);
while (key != 'q') {
if ((bytes = recv(sockClient, (char *)iptr, imgSize , MSG_WAITALL)) == -) {
std::cerr << "recv failed, received bytes = " << bytes << std::endl;
}
cv::imshow("CV Video Client", img);
if (key = cv::waitKey() >= ) break;
}
closesocket(sockClient); WSACleanup(); return ;
}

linux端:
编译命令:

g++ `pkg-config --cflags opencv` -o server -pthread socketServer.cpp `pkg-config --libs opencv`

     #include "opencv2/opencv.hpp"
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "socketSetting.h"
/*
* Created by Wu yongcong 2017-8-25
*
* socket transfer video server
*
*/
using namespace cv;
using namespace std;
void *display(void *);
VideoCapture cap(CAMMER_PORT); // open the default camera
int main(int argc, char** argv)
{
//--------------------------------------------------------
//networking stuff: socket, bind, listen
//--------------------------------------------------------
int localSocket,
remoteSocket,
port = IP_PORT;
struct sockaddr_in localAddr,
remoteAddr;
pthread_t thread_id;
int addrLen = sizeof(struct sockaddr_in);
localSocket = socket(AF_INET , SOCK_STREAM , );
if (localSocket == -){
perror("socket() call failed!!");
}
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = INADDR_ANY;
localAddr.sin_port = htons( port );
if( bind(localSocket,(struct sockaddr *)&localAddr , sizeof(localAddr)) < ) {
perror("Can't bind() socket");
exit();
}
//Listening
listen(localSocket , );
std::cout << "Waiting for connections...\n"
<< "Server Port:" << port << std::endl;
//accept connection from an incoming client
while(){
remoteSocket = accept(localSocket, (struct sockaddr *)&remoteAddr, (socklen_t*)&addrLen);
if (remoteSocket < ) {
perror("accept failed!");
exit();
}
std::cout << "Connection accepted" << std::endl;
pthread_create(&thread_id,NULL,display,&remoteSocket);
//pthread_join(thread_id,NULL);
}
//pthread_join(thread_id,NULL);
//close(remoteSocket);
return ;
}
void *display(void *ptr){
int socket = *(int *)ptr;
//OpenCV Code
//----------------------------------------------------------
Mat img, imgGray,imgColor;
img = Mat::zeros(,,CV_8UC3);
//make it continuous
if (!img.isContinuous()) {
img = img.clone();
}
// int imgSize = img.total() * img.elemSize();
int imgSize = img.total() * img.channels();
int bytes = ;
int key;
//make img continuos
if ( !img.isContinuous() ) {
img = img.clone();
imgGray = img.clone();
}
std::cout << "Image Size:" << imgSize << std::endl;
while() {
/* get a frame from camera */
cap >> img;
if (img.empty()) break;
//cvtColor(img, imgGray, CV_RGB2GRAY); // color change
//send processed image
if ((bytes = send(socket, img.data, imgSize, )) < ){
std::cerr << "bytes = " << bytes << std::endl;
break;
}
}
}