-
Winsock help?
I am learning winsock and I have a problem. Here's the code for my server:
#include <winsock.h>
#include <iostream.h>
#include <stdio.h>
#include <conio.c>
class data
{
public:
int write(SOCKET s, char szBuffer[1000], int len, int flags);
int read(SOCKET s, char szBuffer[1000], int len, int flags);
int end(SOCKET s, int how);
};
int data::write(SOCKET s, char szBuffer[1000], int len, int flags)
{
if(send(s, szBuffer, len, flags) == -1)
{
cout << "\n\nError sending data...";
WSACleanup();
}
}
int data::read(SOCKET s, char szBuffer[1000], int len, int flags)
{
if(recv(s, szBuffer, len, flags) == -1)
{
cout << "\n\nError receiving data...";
WSACleanup();
}
}
int data::end(SOCKET s, int how)
{
shutdown(s, how);
}
int main()
{
data wsdat;
char buff[1000];
int len;
int tmpSock;
SOCKET sockfd;
SOCKADDR_IN saddr;
WSADATA wsaDat;
WSAStartup(0x101, &wsaDat);
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(20123);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(bind(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr)) == -1)
{
cout << "\n\nError binding socket..Error #" << WSAGetLastError();
WSACleanup();
getch();
}
while(tmpSock == SOCKET_ERROR)
{
tmpSock = listen(sockfd, 10);
}
sockfd = tmpSock;
if(connect(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr)) == -1)
{
cout << "\n\nError connecting to socket...Error #" << WSAGetLastError();
WSACleanup();
getch();
}
while(tmpSock == SOCKET_ERROR)
{
tmpSock = accept(sockfd, NULL, NULL);
}
sockfd = tmpSock;
cout << "\n\nConnection accepted...\n\n";
while(tmpSock == SOCKET_ERROR)
{
tmpSock = wsdat.read(sockfd, buff, 1000, 0);
}
cout << buff;
wsdat.end(sockfd, 3);
getch();
return 0;
}
It won't accept the connection from my client. It just waits a certain amount of time and says my error message for connect:
"Error connecting to socket...Error #10061"
What do I do?
-
what you should do is try posting this on the windows programming forum. should have better luck there.
-
I looked up the winsock error code 10061, and it means:
Connection refused.
Maybe someone else here could explain why.
I guess you could try a different port.
-
>>while(tmpSock == SOCKET_ERROR)
{
tmpSock = listen(sockfd, 10);
}
sockfd = tmpSock;
listen does not return a SOCKET but an int. It returns an error code or zero if OK.
So this will always fail
>>if(connect(sockfd, (struct sockaddr *) &saddr, sizeof(struct sockaddr)) == -1)
as sockfd is either zero or an error code.