?? mysocket.cpp
字號:
errMsg.append("with the SO_BROADCAST parameter to allow the use of the broadcast address.");
}
else if ( *errCode == WSAEINTR )
{
errMsg.append("A blocking Windows Sockets 1.1 call was canceled\n");
errMsg.append("through WSACancelBlockingCall.");
}
else if ( *errCode == WSAEINPROGRESS )
{
errMsg.append("A blocking Windows Sockets 1.1 call is in progress,\n");
errMsg.append("or the service provider is still processing a callback function.");
}
else if ( *errCode == WSAEFAULT )
{
errMsg.append("The buf parameter is not completely contained in a\n");
errMsg.append("valid part of the user address space.");
}
else if ( *errCode == WSAENETRESET )
{
errMsg.append("The connection has been broken due to the keep-alive\n");
errMsg.append("activity detecting a failure while the operation was in progress.");
}
else if ( *errCode == WSAENOBUFS )
errMsg.append("No buffer space is available.");
else if ( *errCode == WSAENOTCONN )
errMsg.append("The socket is not connected.");
else if ( *errCode == WSAENOTSOCK )
errMsg.append("The descriptor is not a socket.");
else if ( *errCode == WSAEOPNOTSUPP )
{
errMsg.append("MSG_OOB was specified, but the socket is not stream-style\n");
errMsg.append("such as type SOCK_STREAM, out-of-band data is not supported\n");
errMsg.append("in the communication domain associated with this socket,\n");
errMsg.append("or the socket is unidirectional and supports only receive operations.");
}
else if ( *errCode == WSAESHUTDOWN )
{
errMsg.append("The socket has been shut down; it is not possible to send\n");
errMsg.append("on a socket after shutdown has been invoked with how set\n");
errMsg.append("to SD_SEND or SD_BOTH.");
}
else if ( *errCode == WSAEWOULDBLOCK )
errMsg.append("The socket is marked as nonblocking and the requested operation would block.\n");
else if ( *errCode == WSAEMSGSIZE )
{
errMsg.append("The socket is message oriented, and the message is larger\n");
errMsg.append("than the maximum supported by the underlying transport.");
}
else if ( *errCode == WSAEHOSTUNREACH )
errMsg.append("The remote host cannot be reached from this host at this time.");
else if ( *errCode == WSAEINVAL )
{
errMsg.append("The socket has not been bound with bind, or an unknown flag\n");
errMsg.append("was specified, or MSG_OOB was specified for a socket with SO_OOBINLINE enabled.");
}
else if ( *errCode == WSAECONNABORTED )
{
errMsg.append("The virtual circuit was terminated due to a time-out or \n");
errMsg.append("other failure. The application should close the socket as it is no longer usable.");
}
else if ( *errCode == WSAECONNRESET )
{
errMsg.append("The virtual circuit was reset by the remote side executing a \"hard\" \n");
errMsg.append("or \"abortive\" close. For UPD sockets, the remote host was unable to\n");
errMsg.append("deliver a previously sent UDP datagram and responded with a\n");
errMsg.append("\"Port Unreachable\" ICMP packet. The application should close\n");
errMsg.append("the socket as it is no longer usable.");
}
else if ( *errCode == WSAETIMEDOUT )
{
errMsg.append("The connection has been dropped, because of a network failure\n");
errMsg.append("or because the system on the other end went down without notice.");
}
else errMsg.append("unknown problems!");
}
#endif
void myTcpSocket::connectToServer(string& serverNameOrAddr,hostType hType)
{
/*
when this method is called, a client socket has been built already,
so we have the socketId and portNumber ready.
a myHostInfo instance is created, no matter how the server's name is
given (such as www.yuchen.net) or the server's address is given (such
as 169.56.32.35), we can use this myHostInfo instance to get the
IP address of the server
*/
myHostInfo serverInfo(serverNameOrAddr,hType);
// Store the IP address and socket port number
struct sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(serverInfo.getHostIPAddress());
serverAddress.sin_port = htons(portNumber);
// Connect to the given address
try
{
if (connect(socketId,(struct sockaddr *)&serverAddress,sizeof(serverAddress)) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling connect():\n";
detectErrorConnect(&errorCode,errorMsg);
myException socketConnectException(errorCode,errorMsg);
throw socketConnectException;
#endif
#ifdef UNIX
myException unixSocketConnectException(0,"unix: error calling connect()");
throw unixSocketConnectException;
#endif
}
}
catch(myException& excp)
{
excp.response();
exit(1);
}
}
myTcpSocket* myTcpSocket::acceptClient(string& clientHost)
{
int newSocket; // the new socket file descriptor returned by the accept systme call
// the length of the client's address
int clientAddressLen = sizeof(struct sockaddr_in);
struct sockaddr_in clientAddress; // Address of the client that sent data
// Accepts a new client connection and stores its socket file descriptor
try
{
if ((newSocket = accept(socketId, (struct sockaddr *)&clientAddress,&clientAddressLen)) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling accept(): \n";
detectErrorAccept(&errorCode,errorMsg);
myException socketAcceptException(errorCode,errorMsg);
throw socketAcceptException;
#endif
#ifdef UNIX
myException unixSocketAcceptException(0,"unix: error calling accept()");
throw unixSocketAcceptException;
#endif
}
}
catch(myException& excp)
{
excp.response();
return NULL;
}
// Get the host name given the address
char *sAddress = inet_ntoa((struct in_addr)clientAddress.sin_addr);
myHostInfo clientInfo(string(sAddress),ADDRESS);
char* hostName = clientInfo.getHostName();
clientHost += string(hostName);
// Create and return the new myTcpSocket object
myTcpSocket* retSocket = new myTcpSocket();
retSocket->setSocketId(newSocket);
return retSocket;
}
void myTcpSocket::listenToClient(int totalNumPorts)
{
try
{
if (listen(socketId,totalNumPorts) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling listen():\n";
detectErrorListen(&errorCode,errorMsg);
myException socketListenException(errorCode,errorMsg);
throw socketListenException;
#endif
#ifdef UNIX
myException unixSocketListenException(0,"unix: error calling listen()");
throw unixSocketListenException;
#endif
}
}
catch(myException& excp)
{
excp.response();
exit(1);
}
}
/*
int myTcpSocket::sendMessage(string& message)
{
int numBytes; // the number of bytes sent
char msgLength[MSG_HEADER_LEN+1];
sprintf(msgLength,"%6d",message.size());
string sendMsg = string(msgLength);
sendMsg += message;
// Sends the message to the connected host
try
{
if (numBytes = send(socketId,sendMsg.c_str(),sendMsg.size(),0) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling send():\n";
detectErrorSend(&errorCode,errorMsg);
myException socketSendException = new myException(errorCode,errorMsg);
throw socketSendException;
#endif
#ifdef UNIX
myException unixSocketSendException = new myException(0,"unix: error calling send()");
throw unixSocketSendException;
#endif
}
}
catch(myException& excp)
{
excp.response();
exit(1);
}
return numBytes;
}
*/
int myTcpSocket::sendMessage(string& message)
{
int numBytes; // the number of bytes sent
/*
for each message to be sent, add a header which shows how long this message
is. This header, regardless how long the real message is, will always be
of the length MSG_HEADER_LEN.
*/
char msgLength[MSG_HEADER_LEN+1];
sprintf(msgLength,"%6d",message.size());
string sendMsg = string(msgLength);
sendMsg += message;
// Sends the message to the connected host
try
{
if (numBytes = send(socketId,sendMsg.c_str(),sendMsg.size(),0) == -1)
{
#ifdef WINDOWS_XP
int errorCode = 0;
string errorMsg = "error calling send():\n";
detectErrorSend(&errorCode,errorMsg);
myException socketSendException(errorCode,errorMsg);
throw socketSendException;
#endif
#ifdef UNIX
myException unixSocketSendException(0,"unix: error calling send()");
throw unixSocketSendException;
#endif
}
}
catch(myException& excp)
{
excp.response();
exit(1);
}
return numBytes;
}
#ifdef WINDOWS_XP
/*
int myTcpSocket::XPrecieveMessage(string& message)
{
int numBytes = 0; // The number of bytes received
int currentSize = MSG_HEADER_LEN; // The number of bytes wanted to receive
int offsetSize = 0; // The number of bytes currently recieved
// retrieve the length of the message received
char msgLength[MSG_HEADER_LEN+1];
memset(msgLength,0,sizeof(msgLength));
try
{
while ( numBytes < currentSize )
{
numBytes = recv(socketId,msgLength+offsetSize,currentSize,MSG_PEEK);
if (numBytes == -1)
{
int errorCode = 0;
string errorMsg = "error calling recv():\n";
detectErrorRecv(&errorCode,errorMsg);
myException socketRecvException = new myException(errorCode,errorMsg);
throw socketRecvException;
}
else if ( numBytes < currentSize )
{
offsetSize += numBytes;
currentSize -= numBytes;
}
}
}
catch(myException excp)
{
excp.response();
exit(1);
}
// recieve the real message
currentSize = atoi(msgLength);
offsetSize = 0;
cout << "[RECV:message length] " << msgLength << endl;
winLog << "[RECV:message length] " << msgLength << endl;
try
{
while ( numBytes < currentSize )
{
numBytes = recv(socketId,(char*)(message.c_str())+offsetSize,currentSize,0);
if (numBytes == -1)
{
int errorCode = 0;
string errorMsg = "error calling recv():\n";
detectErrorRecv(&errorCode,errorMsg);
myException socketRecvException = new myException(errorCode,errorMsg);
throw socketRecvException;
}
else if ( numBytes < currentSize )
{
offsetSize += numBytes;
currentSize -= numBytes;
}
}
}
catch(myException& excp)
{
excp.response();
exit(1);
}
cout << "[RECV:message] " << message << endl;
winLog << "[RECV:message] " << message << endl;
return atoi(msgLength);
}
*/
int myTcpSocket::XPrecieveMessage(string& message)
{
int received = 0; // The number of bytes received
int msgSize = MAX_RECV_LEN; // The number of bytes wanted to receive
int numBytes = 0; // The number of bytes currently recieved
int totalRecvNum = 0;
bool headerFinished = false;
char charMsg[MAX_RECV_LEN+1];
char msgLength[MSG_HEADER_LEN+1];
memset(charMsg,0,sizeof(charMsg));
memset(msgLength,0,sizeof(msgLength));
try
{
while ( received < msgSize )
{
numBytes = recv(socketId,charMsg+received,1,0);
if (numBytes == -1)
{
int errorCode = 0;
string errorMsg = "error calling recv():\n";
detectErrorRecv(&errorCode,errorMsg);
myException socketRecvException(errorCode,errorMsg);
throw socketRecvException;
}
if ( !headerFinished )
{
msgLength[received] = *(charMsg+received);
received ++;
if ( received == MSG_HEADER_LEN )
{
headerFinished = true;
received = 0;
memset(charMsg,0,sizeof(charMsg));
msgSize = atoi(msgLength);
}
}
else
received ++;
}
}
catch(myException& excp)
{
if ( excp.getErrCode() == WSAECONNRESET )
{
//cout << "!! your party has shut down the connection... \n";
//winLog << "!! your party has shut down the connection... \n";
return -99;
}
excp.response();
exit(1);
}
message.append(string(charMsg));
return msgSize;
}
#endif
int myTcpSocket::recieveMessage(string& message)
{
int numBytes; // The number of bytes recieved
#ifdef WINDOWS_XP
return XPrecieveMessage(message);
#endif
// retrieve the length of the message received
char msgLength[MSG_HEADER_LEN+1];
memset(msgLength,0,sizeof(msgLength));
try
{
numBytes = recv(socketId,msgLength,MSG_HEADER_LEN,0);
if (numBytes == -1)
{
myException unixSocketRecvException(0,"unix: error calling recv()");
throw unixSocketRecvException;
}
}
catch(myException& excp)
{
excp.response();
exit(1);
}
// receive the real message
try
{
numBytes = recv(socketId,(char*)(message.c_str()),atoi(msgLength),0);
if (numBytes == -1)
{
myException unixSocketRecvException(0,"unix: error calling recv()");
throw unixSocketRecvException;
}
}
catch(myException& excp)
{
excp.response();
exit(1);
}
return numBytes;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -