我想使用select();
实现服务器客户端单线程
对于服务器部分,我从http://www.binarytides.com/code-tcp-socket-server-winsock/获取代码,对于客户端,该站点不提供某些代码,他们使用netcat
来模拟客户端。因此,对于客户端,我使用此代码: -
#include <stdio.h>
#include <winsock2.h
#pragma comment(lib,"ws2_32.lib")
int main(void) {
struct sockaddr_in si_other;
int s, slen=sizeof(si_other);
char buf[512];
char message[512];
WSADATA wsa;
//Initialise winsock
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
exit(EXIT_FAILURE);
}
printf("Initialised.\n");
//create socket
if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
{
printf("socket() failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
//setup address structure
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(8888);
si_other.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
//start communication
while(1)
{
printf("Enter message : ");
gets(message);
//send the message
if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
{
printf("sendto() failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
//receive a reply and print it
//clear the buffer by filling null, it might have previously received data
memset(buf,'\0', BUFLEN);
//try to receive some data, this is a blocking call
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR)
{
printf("recvfrom() failed with error code : %d" , WSAGetLastError());
exit(EXIT_FAILURE);
}
puts(buf);
}
closesocket(s);
WSACleanup();
return 0;
}
即使服务器和客户端具有相同的端口,客户端也总是返回-1,这意味着他不向服务器发送任何消息。有人可以告诉我这里我做错了什么吗?任何提示将不胜感激。
感谢。