我想寫一個簡單的服務器客戶端應用程序,它應該這樣做: 客戶端連接到服務器,服務器等待消息,客戶端從用戶接受輸入,並將其發送到服務器。服務器收到此消息並將其發送回客戶端,客戶端打印消息並循環並重新開始。然而,由於某種原因,我有一個相當奇怪的問題:當我發送第一條消息時,服務器會迴應它,當我發送第二條消息時,服務器會再次響應第一條消息。當我發送我的第三條消息時,服務器以第二條消息的響應等等。簡單的C++服務器客戶端應用程序與winsock
這裏是我的服務器代碼來處理連接:
class themusers {
char ReMessage[200],SeMessage[200];
public:
void * HandleConnections(SOCKET connector,int location) {
std::string Converter;
for (;;) {
if (recv(connector,ReMessage,sizeof(ReMessage),NULL) == -1)
std::cout << "Disconnected." << std::endl;
discon.lock();
sock_connection[location] = NULL;
discon.unlock();
break;
}
else {
//this is the code that handles the receive/send operation
msgmut.lock();
//std:: cout << ReMessage << std::endl;
memcpy(SeMessage, ReMessage, sizeof(ReMessage));
send(connector, SeMessage, sizeof(SeMessage), NULL);
msgmut.unlock();
}
}
return NULL;
}
};
這是我的客戶端代碼:拇指與[TCP] socket編程
for (;;) {
cin >> tell;
send(sock, tell, sizeof(tell), NULL);
recv(sock,Message,sizeof(Message),NULL);
Converter = Message;
cout << "Server: " << Converter << endl;
}
也許與'cin'而不是套接字有關的問題?它不是用緩衝輸入做奇怪的事情嗎? – 2013-03-07 19:54:15
你是不是在服務器代碼中的'if'之後錯過了一個捲曲? – 2013-03-07 19:58:41
不,只是檢查。似乎沒有。 – 2013-03-07 20:00:38