如何从main(winsock)向服务器发送消息
how to send message to server from main (winsock)?
我使用winsock创建了一个简单的客户端-服务器应用程序。我想向服务器发送消息作为对用户输入的响应,但它不起作用。我创建了一个函数sendData(),它将"test"发送到服务器。如果我在连接服务器后立即调用func,它可以正常工作,但如果我从main或其他类调用它,则服务器不接受该消息。
有什么建议吗?
客户代码:
#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: %dn", 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: %dn", WSAGetLastError());
closesocket(m_socket);
WSACleanup();
return false;
}
printf("sending initial message to server!n");
printf("Bytes Sent: %ldn", iResult);
iResult = recv(m_socket, recvbuf, DEFAULT_BUFLEN, 0);
if ( iResult > 0 )
printf("Bytes received: %dn", iResult);
else if ( iResult == 0 )
printf("Connection closedn");
else
printf("recv failed with error: %dn", 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: %dn", 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: %dn", 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(): %ldn", 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 functionn");
iResult = recv(m_clientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf("Bytes received: %dn", 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: %dn", WSAGetLastError());
closesocket(m_clientSocket);
WSACleanup();
return false;
}
printf("Bytes sent: %dn", iSendResult);
}
else if (iResult == 0) {
printf("Connection closing...n");
}
else {
printf("recv failed: %dn", 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: %dn", 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: %dn", 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(): %ldn", 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: %dn", 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: %ldn", 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: %dn", 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);
}
谢谢!
我发现了问题。我调用init()函数两次,它断开了连接:|
相关文章:
- 从服务器传输到客户端的消息不会出现
- 如何将 Firebase 与基于 Linux 的客户端应用配合使用,以便与服务器进行双向消息通信
- 来自带有mbedtls TLS的Mongoose Web服务器的错误消息
- C++ UDP 服务器在获取客户端地址配置时发送消息
- 如何使用标准库网络 TS 在服务器和客户端之间发送消息C++
- 客户端发送消息,但服务器在客户端结束程序之前不接收消息
- 使 gRPC 客户端处于侦听模式,以侦听来自服务器的消息
- 浏览器将随机HTTP消息正文发送到我的boost.asio服务器.我可以更改此设置吗?
- 多线程套接字编程服务器仅从 1 个客户端线程获取消息
- 将 API 链接消息解析为 C (Arduino IDE) 中的服务器
- 无法使用C#TCP服务器和C TCP客户端接收消息
- Datagram套接字服务器未从客户端接收消息
- boost/asio:非常简单的聊天服务器无法访问收到的消息
- 服务器进程等待客户端输入/消息的最佳方法是什么?
- 为什么我的android客户端无法接收到来自winsock c++服务器的字符串消息
- C 客户端和Java服务器消息
- 将消息从C 服务器发送到Java客户端
- 如何从main(winsock)向服务器发送消息
- 客户端-服务器消息解释
- 将我的服务器响应char数组转换为wchar_t数组是处理客户端收到的服务器消息的正确方法吗?