0
//下面的代码工作正常,但用于发送字符串。为了发送包含具有不同数据类型字段的标题的缓冲区(缓冲区地址),我必须做什么更改? (我是新来编程。所以,原谅小白的我)TCP套接字程序发送一个缓冲区。
ClientSocket.cpp
ClientSocket::ClientSocket (std::string host, int port)
{
if (! Socket::create())
{
throw SocketException ("Could not create client socket.");
}
if (! Socket::connect (host, port))
{
throw SocketException ("Could not connect.");
}
}
const ClientSocket& ClientSocket::operator << (const std::string& s) const
{
if (! Socket::send (s))
{
throw SocketException ("Could not write to socket.");
}
return *this;
}
const ClientSocket& ClientSocket::operator >> (std::string& s) const
{
if (! Socket::recv (s))
{
throw SocketException ("Could not read from socket.");
}
return *this;
}
simple_client_main.cpp
#include "ClientSocket.h"
#include "SocketException.h"
#include <iostream>
#include <string>
int main (int argc, int argv[])
{
try
{
ClientSocket client_socket ("169.254.103.63", 30000);
std::string reply;
try
{
client_socket << "Test message.";
client_socket >> reply;
}
catch (SocketException&) {}
std::cout << "We received this response from the server:\n\"" << reply << "\"\n";;
}
catch (SocketException& e)
{
std::cout << "Exception was caught:" << e.description() << "\n";
}
return 0;
}
ServerSocket.cpp
// Implementation of the ServerSocket class
#include "ServerSocket.h"
#include "SocketException.h"
ServerSocket::ServerSocket (int port)
{
if (! Socket::create())
{
throw SocketException ("Could not create server socket.");
}
if (! Socket::bind (port))
{
throw SocketException ("Could not bind to port.");
}
if (! Socket::listen())
{
throw SocketException ("Could not listen to socket.");
}
}
ServerSocket::~ServerSocket()
{
}
const ServerSocket& ServerSocket::operator << (const std::string& s) const
{
if (! Socket::send (s))
{
throw SocketException ("Could not write to socket.");
}
return *this;
}
const ServerSocket& ServerSocket::operator >> (std::string& s) const
{
if (! Socket::recv (s))
{
throw SocketException ("Could not read from socket.");
}
return *this;
}
void ServerSocket::accept (ServerSocket& sock)
{
if (! Socket::accept (sock))
{
throw SocketException ("Could not accept socket.");
}
}
simple_server_main.cpp
#include "ServerSocket.h"
#include "SocketException.h"
#include <string>
#include <iostream>
int main (int argc, int argv[])
{
std::cout << "running....\n";
try
{
// Create the socket
ServerSocket server (30000);
while (true)
{
ServerSocket new_sock;
server.accept (new_sock);
try
{
while (true)
{
std::string data;
new_sock >> data;
new_sock << data;
}
}
catch (SocketException&) {}
}
}
catch (SocketException& e)
{
std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";
}
return 0;
}