我试图用c ++制作一个简单的irc客户端。我正在发送PASS,NICK和USER消息,但服务器并没有发送给我PING。我不能注册......
这是代码:
#include <iostream>
#include <string>
#include <WS2tcpip.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
string ipadress = "91.217.189.58";
int port = 6667;
WSADATA ws_data;
SOCKET Skt;
int main()
{
int ws_result = WSAStartup(MAKEWORD(2, 2), &ws_data);
if (ws_result != 0)
cout << "socket cannot be initialized\n";
else
cout << "Soket initialized!\n";
Skt = socket(AF_INET, SOCK_STREAM, 0);
if (Skt == INVALID_SOCKET)
cout << "socket not created\n";
else
cout << "Socket created!\n";
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(6667);
inet_pton(AF_INET, ipadress.c_str(), &hint.sin_addr);
int connection_result = connect(Skt, (sockaddr*)&hint, sizeof(hint));
if (connection_result == SOCKET_ERROR)
cout << "Socket could not connect\n";
else
cout << "Socket Connected!\n";
string channel = "JOIN #dikes\r\n";
string Pass = "PASS PASSRE";
string user = "USER guest 0 * :IRCbot\r\n";
string nick = "NICK botzzz\r\n";
char buffer[4096];//buffer to recieve messages from irc server
send(Skt, Pass.c_str(), Pass.size(), 0);
send(Skt, nick.c_str(), nick.size() , 0);
send(Skt, user.c_str(), user.size(), 0);
while (true)
{
string Pong = "PONG";
ZeroMemory(buffer, 4096);
int bytes_recieved = recv(Skt, buffer, 4096, 0);
string msg = string(buffer, 0, bytes_recieved);
cout << msg;
if (msg == "PING")
{
send(Skt, Pong.c_str(), Pong.size() + 1, 0);
}
else if (msg == "001")
{
send(Skt, channel.c_str(), channel.size(), 0);
}
}
这是此代码的输出:
Soket initialized!
Socket created!
Socket Connected!
:irc.portlane.se 020 * :Please wait while we process your connection.
ERROR :Closing Link: [[email protected]] (Ping timeout)
\r\n
PING
commandPASS
命令没有被\r\n
终止PONG
回应没有被\r\n
终止recv
的单次调用很可能(甚至可能)用从零到多个完整命令/消息的数据填充缓冲区,可能后面是不完整的消息!
TCP / IP不了解IRC协议;它不关心它的“命令”的概念,它不会将数据包分解为那些逐项的部分。你必须这样做。 TCP / IP只会向您传输字节。
您需要在接收到的时将接收的字节添加到辅助缓冲区,然后迭代地解析该缓冲区以提取任何已变为可用的完整行。 (这样做得恰到好处,它也会照顾#1)(但是,我仍然希望在输出中看到ping请求,所以其他一些东西也必须是错误的。)