我写了两个程序,一个作为服务器,另一个作为客户端。服务器使用WinSock2.h
以标准C ++编写。它是一个简单的 echo 服务器,这意味着服务器响应它接收回客户端的内容。我为每个客户端的连接和每个线程使用了一个新线程:
Socket* s = (Socket*) a;
while (1) {
std::string r = s->ReceiveLine()
if (r.empty()) {
break;
}
s->SendLine(r);
}
delete s;
return 0;
Socket
是来自here的课程。服务器运行正常,我使用telnet
对其进行了测试,效果很好。
然后我使用C ++ .NET(或C ++ / CLI)编写客户端,TcpClient
用于从服务器发送和接收消息。代码如下:
String^ request = "test";
TcpClient ^ client = gcnew TcpClient(server, port);
array<Byte> ^ data = Encoding::ASCII->GetBytes(request);
NetworkStream ^ stream = client->GetStream();
stream->Write(data, 0, data->Length);
data = gcnew array<Byte>(256);
String ^ response = String::Empty;
int bytes = stream->Read(data, 0, data->Length);
response = Encoding::ASCII->GetString(data, 0, bytes);
client->Close();
当我运行客户端并尝试在表单上显示响应消息时,程序在行int bytes = stream->Read(data, 0, data->Length);
处停止,无法获取响应。服务器正在运行,并且与网络无关,因为它们都在同一台计算机上运行。
我想原因是数据服务器的响应时间小于data->Length
,因此Read
方法正在等待更多数据。是对的吗?我该如何解决这个问题?
我想我已经解决了问题...... Socket
类中有另外两种方法,ReceiveBytes
和SendBytes
,这两种方法都不会删除未使用的空间在bytes数组中。因此,从服务器返回的数据长度将与客户端的数据长度匹配,因此Read
方法不会等待更多数据到来。
答案 0 :(得分:0)
std::string Socket::ReceiveLine() {
std::string ret;
while (1) {
char r;
switch(recv(s_, &r, 1, 0)) {
case 0: // not connected anymore;
// ... but last line sent
// might not end in \n,
// so return ret anyway.
return ret;
case -1:
return "";
// if (errno == EAGAIN) {
// return ret;
// } else {
// // not connected anymore
// return "";
// }
}
ret += r;
if (r == '\n') return ret;
}
}
我猜服务器的接收线功能正在等待输入密钥&#39; \ n&#39;。
尝试使用&#34; test \ n&#34;字符串。
String^ request = "test\n";
// other codes....