我會保持簡單。
代碼:C服務器套接字接受沒有請求的客戶端
#include "stdafx.h"
#include <winsock2.h>
#include <conio.h>
#include <iostream>
#include <stdio.h>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsadata;
int error = WSAStartup(0x0202, &wsadata);
if(error) printf("WinSock error!");
SOCKET server;
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5657);
server_addr.sin_addr.s_addr = htonl (INADDR_ANY);
server = socket(AF_INET, SOCK_STREAM, 0);
if (server == INVALID_SOCKET) printf("INVALID SOCKET!");
error = bind(server, (LPSOCKADDR)&server_addr, sizeof(server_addr));
if(error) printf("Connect Error!");
listen(server, SOMAXCONN);
printf("SERVER ESTABLISHED! LISTENING...\n");
sockaddr_in client_addr;
SOCKET client;
client = accept(server, (struct sockaddr*)&client_addr, (int *)sizeof(client_addr));
if(client==INVALID_SOCKET) printf("INVALID SOCKET!\n");
printf("A CLIENT!");
closesocket(server);
WSACleanup();
getch();
return 0;
}
但我得到的是:
服務器上設定!聆聽... 無效SOCKET! 客戶!
我已經在C#中完成了套接字,我猜服務器應該監聽並等待客戶端,並且每當客戶端請求連接時,服務器都應該接受它,但服務器不等待就接受套接字,這個接受的套接字也是無效的!爲什麼會發生這種情況,我該如何解決?
WSAGetLastError()返回什麼? – hmjd