嘿家伙,这里是我的代码。C++奇怪的套接字数据
int main() {
char buffer[BUFSIZE];
// define our address structure, stores our port
// and our ip address, and the socket type, etc..
struct sockaddr_in addrinfo;
addrinfo.sin_family = AF_INET;
addrinfo.sin_port = htons(PORT);
addrinfo.sin_addr.s_addr = INADDR_ANY;
// create our socket.
int sock;
if ((sock = socket(addrinfo.sin_family, SOCK_STREAM, 0)) < 0) {
cout << "Error in creating the socket.";
}
// bind our socket to the actual adress we want
if (bind(sock, (struct sockaddr*)&addrinfo, sizeof(addrinfo)) != 0) {
cout << "Error in binding.";
}
// open the socket up for listening
if (listen(sock, 5) != 0) {
cout << "Error in opening listener.";
}
cout << "Waiting for connections...." << endl;
char *msg = "Success! You are connected.\r\n";
// continuously accept new connections.. but no multithreading.. yet
while(1) {
struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(client_addr);
if(int client = accept(sock, (struct sockaddr*)&client_addr, &sin_size)) {
cout << "Recived new connection from " << inet_ntoa(client_addr.sin_addr) << endl;
send(client, msg, strlen(msg), 0);
while(1) {
send(client, buffer, recv(client, buffer, BUFSIZE, 0), 0);
cout << buffer << endl;
strcpy(buffer, "");
}
} else {
cout << "Error in accepting new connection." << endl;
}
}
close(sock);
return 0;
}
现在,我很新的插座,我只是那种试图让他们的感觉,但我有与PHP插座一些经验。我在我的linux机器上通过putty使用telnet来测试这个,我不知道是否会导致任何问题,但服务器正在输出一些奇怪的字符,我不知道为什么。我认为这与缓冲区有关,但我不确定。我可以通过telnet发送诸如“hi”之类的东西到服务器,它会输出它们并将它们发回给我,但当我发送诸如“hoobla”之类的东西时,它会启动时髦的字符。任何的意见都将会有帮助!
提前致谢!
好吧,所以recv实际返回它包含的字节大小? – 2010-08-11 05:04:30
是的,或者错误-1或0如果另一端关闭连接,这两个代码在这里均等对待。 – paxdiablo 2010-08-11 05:10:16