C++编码实现TCP ,效果如图
这是client的
这是server的
以下是server源代码
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include
#include
#include
#include
#include
#include
#include
#pragma comment (lib, "ws2_32.lib")
#define portnum 16000
#define BUFFER_SIZE 1024
#define BOARD_BUFFER_SIZE 100
using std::cout;
using namespace std;
vector Board;
int make_socket(int port)
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
cout << "DLL initializes error" << endl;
return 0;
}
SOCKET servSock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = PF_INET;
sockAddr.sin_addr.s_addr = INADDR_ANY;
sockAddr.sin_port = htons(port);
if (bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR)) == SOCKET_ERROR)
{
cout << "bind error!" << endl;
return 0;
}
if (listen(servSock, 5) == SOCKET_ERROR)
{
cout << "listen error!" << endl;
return 0;
}
return servSock;
}
void POST(vector split_message)
{
int i;
for (i = 1; i < split_message.size()-1; i++)
{
if (Board.size() < BOARD_BUFFER_SIZE)
{
Board.push_back(split_message[i]);
}
}
}
void READ(int sClient)
{
int i;
cout << "Board.size():" << Board.size() << endl;
for (i = 0; i < Board.size(); i++)
{
cout << "reading: sending " << Board[i].c_str() << endl;
if (send(sClient, Board[i].c_str(), strlen(Board[i].c_str()), 0) < 0)
{
cout << "Server: Send meassage \"" << Board[i].c_str() << "\" failed." <<endl;
}
else
{
Sleep(100);
}
}
if (send(sClient, ".", sizeof("."), 0) < 0)
{
cout << "Server: Send meassage . failed." << endl;
}
}
void handle_accept(int sClient)
{
char ok_message[3] = "OK";
char error_message[31] = "ERROR - Command not understood";
char buffer[BUFFER_SIZE];
memset(buffer, 0, BUFFER_SIZE);
const char* delim = "\n";
while (true)
{
// cout << "Receiving...\n" << endl;
int len = recv(sClient, buffer, BUFFER_SIZE, 0);
if (len <= 0)
{
continue;
}
cout << "Client send " << buffer << endl;
if (strcmp(buffer, "QUIT\n") == 0)
{
if (send(sClient, ok_message, strlen(ok_message), 0) < 0)
{
cout << "Server: Send OK meassage failed." << endl;
}
break;
}
vector<string> split_message;
char* p = strtok(buffer, delim);
while ( p )
{
string s = p;
split_message.push_back(s);
p = strtok(NULL, delim);
}
cout << "Command" << split_message[0] << endl;
if (split_message[0] == "POST")
{
POST(split_message);
for (int i = 0; i < Board.size(); i++)
{
cout << "Board message " << i << ":" << Board[i] << endl;
}
if (send(sClient, ok_message, sizeof(ok_message), 0) < 0)
{
cout << "Server: Send OK meassage failed." << endl;
}
}
else if (split_message[0] == "READ")
{
cout << "reading" << endl;
READ(sClient);
}
else
{
if (send(sClient, error_message, sizeof(error_message), 0) < 0)
{
cout << "Server: Send error meassage failed." << endl;
}
else
{
continue;
}
}
memset(buffer, 0, BUFFER_SIZE);
}
closesocket(sClient);
}
int main() {
int servSock = make_socket(portnum);
while (true)
{
int socket_feed = accept(servSock, nullptr, nullptr);
handle_accept(socket_feed);
}
WSACleanup();
return 0;
}