serverSocket = socket(socket.AF_INET, socket.SOCK_STREAM)
时间: 2023-05-17 10:04:35 浏览: 152
这是一个 Python 代码片段,用于创建一个 TCP 服务器套接字。其中,socket.AF_INET 表示使用 IPv4 地址族,socket.SOCK_STREAM 表示使用面向连接的 TCP 协议。
相关问题
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #include <signal.h> int serverSocket,clientSocket; void hand(int val){ //7. 关闭连接 close(serverSocket); close(clientSocket); printf("bye bye!\n"); exit(0); } int main(int argc,char* argv[]){ if(argc != 3) printf("请输入ip地址和端口号!\n"),exit(0); printf("ip: %s port:%d\n",argv[1],atoi(argv[2])); signal(SIGINT,hand); //1. 创建socket 参数一: 协议类型(版本) 参数二: 通信媒介 参数三: 保护方式 serverSocket = socket(AF_INET,SOCK_STREAM,0); if(-1 == serverSocket) printf("创建socket失败:%m\n"),exit(-1); printf("创建socket成功!\n"); //2. 创建服务器协议地址簇 struct sockaddr_in sAddr = { 0 }; sAddr.sin_family = AF_INET; //协议类型 和socket函数第一个参数一致 sAddr.sin_addr.s_addr = inet_addr(argv[1]); //将字符串转整数 sAddr.sin_port = htons(atoi(argv[2])); //将字符串转整数,再将小端转换成大端 //3. 绑定服务器协议地址簇 int r = bind(serverSocket,(struct sockaddr*)&sAddr,sizeof sAddr); if(-1 == r) printf("绑定失败:%m\n"),close(serverSocket),exit(-2); printf("绑定成功!\n"); //4. 监听 r = listen(serverSocket,10); if(-1 == r) printf("监听失败:%m\n"),close(serverSocket),exit(-3); printf("监听成功!\n"); //5. 接收客户端连接 struct sockaddr_in cAddr = {0}; int len = sizeof(sAddr); clientSocket = accept(serverSocket,(struct sockaddr*)&cAddr,&len); if(-1 == clientSocket) printf("接收客户端连接失败:%m\n"),close(serverSocket),exit(-1); printf("有客户端连接上服务器了: %s\n",inet_ntoa(cAddr.sin_addr)); //6. 通信 char buff[256] = {0}; while(1){ r = recv(clientSocket,buff,255,0); if(r > 0){ buff[r] = 0; printf("客户端说>> %s\n",buff); } } return 0; }
这段代码是一个简单的TCP服务器程序,它创建了一个socket,并在指定的IP地址和端口上监听客户端的连接请求。当客户端连接服务器时,服务器会接受连接请求并与客户端建立通信。在通信过程中,服务器会不断接收客户端发送过来的数据,并将其打印出来。当客户端关闭连接时,服务器会退出程序。
需要注意的是,这段代码中存在一些问题,例如没有处理客户端关闭连接的情况,也没有进行数据的发送操作。如果需要实现一个完整的聊天程序,还需要进一步完善。
修改以下代码使其能够接受视频并保存到本地,上传到数据库void ShowVideo() { //创建数据库连接 MYSQL mysql; mysql_init(&mysql); mysql_real_connect(&mysql, "localhost", "root", "123456", "myserver", 3306, NULL, 0); mysql_query(&mysql, "set names utf8"); SOCKET server = socket(AF_INET, SOCK_STREAM, 0); char buffer[2048] = " "; SOCKET sockConn = accept(server, NULL, NULL); Mat videoData; while (true) { int bytes = recv(sockConn, buffer, 2048, 0); if (bytes <= 0) break; // 将接收到的视频数据拼接在一起 videoData.push_back(Mat(1, bytes, CV_8UC1, buffer).clone()); } closesocket(sockConn); //size_t fileSize = 0; std::ofstream videoFile("server_video.avi", std::ios::binary | std::ios::app); while (true) { int bytes = recv(sockConn, buffer, 2048, 0); if (bytes <= 0) break; //fileSize += bytes; // 将接收到的视频数据写入到.avi文件中 //std::ofstream videoFile("server_video.avi", std::ios::binary | std::ios::app); videoFile.write(buffer, bytes); } videoFile.close(); VideoWriter writer("server_video.avi", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), 25.0, Size(640, 480)); if (writer.isOpened()) { //writer.write(videoData); cout << "打开失败" << endl; return; } //读取视频文件内容并保存到数据库 ifstream fin("server_video.avi", ios::binary | ios::in); if (!fin) { cout << "打开文件失败" << endl; exit(0); } fin.seekg(0, ios::end); int filesize = fin.tellg(); fin.seekg(0, ios::beg); char* fileContent = new char[filesize]; fin.read(fileContent, filesize); string fileContentStr(fileContent, filesize); //将视频内容上传到数据库 string strSql = "INSERT INTO videos(content) VALUES('"+ fileContentStr + "')"; mysql_query(&mysql, strSql.c_str()); delete[] fileContent; fin.close(); mysql_close(&mysql); closesocket(sockConn); closesocket(server); WSACleanup(); }
注:为了确保代码的正确性和安全性,以下是修改后的代码:
```cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
#include <winsock.h>
#include <mysql.h>
#include <opencv2/opencv.hpp>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "libmysql.lib")
void SaveVideoToDatabase(const std::string& videoPath, MYSQL* mysql) {
std::ifstream file(videoPath, std::ios::in | std::ios::binary);
if (file) {
file.seekg(0, std::ios::end);
std::streampos fileSize = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> videoData(fileSize);
file.read(videoData.data(), fileSize);
file.close();
std::string videoDataStr(videoData.data(), fileSize);
std::string strSql = "INSERT INTO videos(content) VALUES('" + videoDataStr + "')";
if (mysql_query(mysql, strSql.c_str()) != 0) {
std::cerr << "Failed to save video to database." << std::endl;
}
else {
std::cout << "Video saved to database successfully." << std::endl;
}
}
else {
std::cerr << "Failed to open video file." << std::endl;
}
}
void ShowVideo() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Failed to initialize winsock." << std::endl;
return;
}
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Failed to create socket." << std::endl;
WSACleanup();
return;
}
sockaddr_in serverAddress{};
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(12345); // 修改为服务端的端口号
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(serverSocket, reinterpret_cast<sockaddr*>(&serverAddress), sizeof(serverAddress)) != 0) {
std::cerr << "Failed to bind socket." << std::endl;
closesocket(serverSocket);
WSACleanup();
return;
}
if (listen(serverSocket, 1) != 0) {
std::cerr << "Failed to listen on socket." << std::endl;
closesocket(serverSocket);
WSACleanup();
return;
}
std::cout << "Waiting for client connection..." << std::endl;
SOCKET clientSocket = accept(serverSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET) {
std::cerr << "Failed to accept client connection." << std::endl;
closesocket(serverSocket);
WSACleanup();
return;
}
std::vector<char> videoData;
char buffer[2048];
int bytesRead = 0;
while ((bytesRead = recv(clientSocket, buffer, sizeof(buffer), 0)) > 0) {
videoData.insert(videoData.end(), buffer, buffer + bytesRead);
}
closesocket(clientSocket);
closesocket(serverSocket);
WSACleanup();
std::string videoPath = "server_video.avi"; // 修改为要保存的视频文件路径
std::ofstream videoFile(videoPath, std::ios::binary);
if (videoFile) {
videoFile.write(videoData.data(), videoData.size());
videoFile.close();
std::cout << "Video saved successfully." << std::endl;
MYSQL mysql;
mysql_init(&mysql);
if (mysql_real_connect(&mysql, "localhost", "root", "123456", "myserver", 3306, NULL, 0) != NULL) {
std::cout << "Connected to MySQL database." << std::endl;
SaveVideoToDatabase(videoPath, &mysql);
mysql_close(&mysql);
}
else {
std::cerr << "Failed to connect to MySQL database." << std::endl;
}
}
else {
std::cerr << "Failed to save video." << std::endl;
}
}
```
请确保以下几点:
1. 修改 `serverAddress.sin_port` 为服务端的端口号。
2. 修改 `videoPath` 为要保存的视频文件路径。
3. 修改 `mysql_real_connect` 函数的参数来连接到正确的 MySQL 数据库。
注意:这是一个简单的示例代码,仅展示了如何接收视频数据并将其保存到本地和上传到数据库。实际情况可能需要进行更多的错误处理和安全性考虑。
阅读全文