如何从主(winsock)向服务器发送消息?
Posted
技术标签:
【中文标题】如何从主(winsock)向服务器发送消息?【英文标题】:how to send message to server from main (winsock)? 【发布时间】:2015-03-22 19:05:17 【问题描述】:我使用winsock 创建了一个简单的客户端-服务器应用程序。 我想向服务器发送消息作为对用户输入的响应 - 但它不起作用。 我创建了一个函数 sendData(),它将“测试”发送到服务器。 如果我在连接服务器后立即调用 func - 它工作正常,但如果我从主类或其他类调用它 - 服务器不接受消息。
有什么建议吗?
客户端代码:
#include "StdAfx.h"
#include "CommHandler.h"
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFLEN 512
SOCKET CommHandler::m_socket = INVALID_SOCKET;
CommHandler::CommHandler(void)
init();
//===============================================================
CommHandler::~CommHandler(void)
// cleanup
closesocket(m_socket);
WSACleanup();
//===============================================================
bool CommHandler::init()
return (establishConnection("127.0.0.1"));
//===============================================================
bool CommHandler::sendData()
if (m_socket == INVALID_SOCKET)
printf("send msg failed; INVALID_SOCKET: %d\n", WSAGetLastError());
return false;
int recvbuflen = DEFAULT_BUFLEN;
char *sendbuf = "this is a test";
char recvbuf[DEFAULT_BUFLEN];
// Send an initial buffer
int iResult = send(m_socket, sendbuf, (int) strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR)
printf("send failed: %d\n", WSAGetLastError());
closesocket(m_socket);
WSACleanup();
return false;
printf("sending initial message to server!\n");
printf("Bytes Sent: %ld\n", iResult);
iResult = recv(m_socket, recvbuf, DEFAULT_BUFLEN, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
return true;
//===============================================================
bool CommHandler::establishConnection(const std::string ip)
return (initWinsock() && createSocket(ip));
//===============================================================
bool CommHandler::initWinsock()
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2,2), &m_wsaData);
if (iResult != 0)
printf("WSAStartup failed: %d\n", iResult);
return false;
printf("WSAStartup succeeded.\n");
return true;
//===============================================================
bool CommHandler::createSocket(const std::string ip)
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
int iResult = getaddrinfo(ip.c_str(), DEFAULT_PORT, &hints, &result);
if (iResult != 0)
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return false;
// Attempt to connect to the first address returned by
// the call to getaddrinfo
ptr=result;
// Create a SOCKET for connecting to server
m_socket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (m_socket == INVALID_SOCKET)
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return false;
printf("socket creation succeeded.\n");
// Connect to server.
iResult = connect( m_socket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR)
closesocket(m_socket);
m_socket = INVALID_SOCKET;
freeaddrinfo(result);
if (m_socket == INVALID_SOCKET)
printf("Unable to connect to server!\n");
WSACleanup();
return false;
printf("connected to server!\n");
// Send an initial buffer
sendData(); //this send data is received by the server
sendData(); //this send data is received by the server
return true;
服务器代码:
#include "StdAfx.h"
#include "CommHandler.h"
#define DEFAULT_PORT "27015"
#define DEFAULT_BUFLEN 512
CommHandler::CommHandler(void):m_listenSocket(INVALID_SOCKET), m_clientSocket(INVALID_SOCKET)
//===============================================================
CommHandler::~CommHandler(void)
//===============================================================
bool CommHandler::init()
if (establishConnection())
return (receiveData());
return false;
//===============================================================
bool CommHandler::receiveData()
char recvbuf[DEFAULT_BUFLEN];
int iResult, iSendResult;
int recvbuflen = DEFAULT_BUFLEN;
// Receive until the peer shuts down the connection
do
printf("in receiveData function\n");
iResult = recv(m_clientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0)
printf("Bytes received: %d\n", iResult);
std::cout<<recvbuf<<std::endl;
// Echo the buffer back to the sender
iSendResult = send(m_clientSocket, recvbuf, iResult, 0);
if (iSendResult == SOCKET_ERROR)
printf("send failed: %d\n", WSAGetLastError());
closesocket(m_clientSocket);
WSACleanup();
return false;
printf("Bytes sent: %d\n", iSendResult);
else if (iResult == 0)
printf("Connection closing...\n");
else
printf("recv failed: %d\n", WSAGetLastError());
closesocket(m_clientSocket);
WSACleanup();
return false;
while (iResult > 0);
printf("exit receiveData function with no errors (finish while)\n");
return true;
//===============================================================
bool CommHandler::establishConnection()
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2,2), &m_wsaData);
if (iResult != 0)
printf("WSAStartup failed: %d\n", iResult);
return false;
printf("WSAStartup succeeded.\n");
struct addrinfo *result = NULL, *ptr = NULL, hints;
ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET; //used to specify the IPv4 address family
hints.ai_socktype = SOCK_STREAM; //used to specify a stream socket
hints.ai_protocol = IPPROTO_TCP; //used to specify the TCP protocol
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
int iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0)
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return false;
// Create a SOCKET for the server to listen for client connections
m_listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (m_listenSocket == INVALID_SOCKET)
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return false;
printf("socket creation succeeded.\n");
//bind the socket:
// Setup the TCP listening socket
iResult = bind( m_listenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR)
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(m_listenSocket);
WSACleanup();
return false;
freeaddrinfo(result);
printf("bind the socket.\n");
//listen the socket
if ( listen( m_listenSocket, SOMAXCONN ) == SOCKET_ERROR )
printf( "Listen failed with error: %ld\n", WSAGetLastError() );
closesocket(m_listenSocket);
WSACleanup();
return false;
printf("listen the socket.\n");
// Accept a client socket
m_clientSocket = accept(m_listenSocket, NULL, NULL);
if (m_clientSocket == INVALID_SOCKET)
printf("accept failed: %d\n", WSAGetLastError());
closesocket(m_listenSocket);
WSACleanup();
return false;
printf("accept client socket.\n");
return true;
客户的主要:
int main()
CommHandler ch;
if (!ch.init())
return 1;
ch.sendData(); //this msg isn't received by server !!!
system("pause");
return(0);
谢谢!
【问题讨论】:
【参考方案1】:我发现了问题。我调用了两次 init() 函数,它破坏了连接:|
【讨论】:
以上是关于如何从主(winsock)向服务器发送消息?的主要内容,如果未能解决你的问题,请参考以下文章
如何用UDP 实现服务器广播发送,并接收客户端点对点回复,用winsock实现,写出关键代码,谢谢~