以下是服務端的代碼:
#include "stdafx.h"
#include "winsock2.h"
#include "iostream"
#pragma comment (lib,"ws2_32")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
cout << "開始創建套接字\n";
SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in saddrin;
saddrin.sin_addr.S_un.S_addr = inet_addr("INADDR_ANY");
saddrin.sin_port = htons(9100);
cout << "開始綁定\n";
bind(s, (sockaddr *)&saddrin, sizeof(saddrin));
cout << "開始監聽\n";
listen(s, SOMAXCONN);
struct sockaddr_in sClient;
int num = sizeof(sClient);
SOCKET client= accept(s, (sockaddr *)&sClient, &num);
if (client)
{
cout << "已接受來自客戶端的連接\n";
cout << sClient.sin_port<<'\n';
cout<< inet_ntoa(sClient.sin_addr)<<'\n';
char msg[MAXBYTE] = { 0 };
recv(client, msg, sizeof(msg), 0);
cout << msg;
strcpy_s(msg, "this is a reply for the test\n");
send(client, msg, strlen(msg) + sizeof(char), 0);
cout << "已發送消息\n";
}
else
{
cout << "無客戶端的連接";
}
system("PAUSE");
return 0;
}
運行結果如下:
啟動了服務端,客戶端都沒啟動,就直接執行完返回了,accept那裡不是應該阻塞,等待客戶端的連接的嗎?即使同時啟動客戶端和服務端也是這樣的結果,請問應該怎麼解決?
細看了一下你的輸出,程序已經收到請求,所accept接收請求後繼續運行了。