我想知道为什么我没有收到服务器的即时反馈,以及客户端没有从服务器接收数据的原因。
- 这是我服务器的相关代码
//create a connection socket and connect to oncoming request
SOCKET connectionSocket;
while (1){
connectionSocket = SOCKET_ERROR;
while (connectionSocket == SOCKET_ERROR)
{
connectionSocket = connect(sockDescript, NULL, NULL);
if (connectionSocket == 0){
printf("Client connected\n");
sockDescript = connectionSocket;
break;
}
}
break;
}
//Send receive stuff
int bytesSent = SOCKET_ERROR;
int bytesReceived = SOCKET_ERROR;
char bytesToSend[] = "This is Alan's server";
char bytesToReceive[300];
while (bytesReceived == SOCKET_ERROR){
bytesReceived = recv(sockDescript, bytesToReceive, 300, 0);
if (bytesReceived == SOCKET_ERROR)
{
printf("No bytes received\n");
printf("%u", WSAGetLastError());
WSACleanup();
break;
}
else
{
printf("RECEIVED : %u\n", bytesReceived);
printf("Here is the data : %u\n", bytesToReceive);
}
}
while (bytesSent == SOCKET_ERROR)
{
bytesSent = send(sockDescript, bytesToSend, strlen(bytesToSend), 0);
if (bytesSent == SOCKET_ERROR)
{
printf("Failed to send bytes\n");
}
else
{
printf("Bytes were sent\n");
}
}
system("pause");
}
- 这是客户端的代码
//create a socket for connections
SOCKET sockDescriptor;
sockDescriptor = sockDescriptor = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( sockDescriptor== INVALID_SOCKET){
printf("SOCKET creation failed\n");
}
else
{
printf("Socket created succesfully\n");
}
//connect to a server
SOCKADDR_IN clientSocket;
clientSocket.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
clientSocket.sin_port = htons(5555);
clientSocket.sin_family = AF_INET;
if ((connect(sockDescriptor, (SOCKADDR*)&clientSocket, sizeof(clientSocket))) == SOCKET_ERROR)
{
printf("Connection failed\n");
WSACleanup();
return;
}
else
{
printf("Connection established\n");
}
//SEND AND RECEIVE DATA
int bytesSent = SOCKET_ERROR;
int bytesReceived = SOCKET_ERROR;
char bytesToSend[] = "Hello there Server reply if ya hear me";
char bytesRev[200];
while (bytesSent == SOCKET_ERROR)
{
bytesSent = send(sockDescriptor, bytesToSend, strlen(bytesToSend), 0);
if (bytesSent == SOCKET_ERROR){
printf("Data delivery was unsuccessful");
}
else
{
printf("Data sent\n");
}
}
while(bytesReceived == SOCKET_ERROR)
{
bytesReceived = recv(sockDescriptor, bytesRev, 32, 0);
if (bytesReceived == 0 || bytesReceived == WSAECONNRESET){
printf("NO bytes returned or connection reset\n");
}
else
{
printf("here is the returned message\n : %u\n", bytesRev);
break;
}
}
}
- 来自服务器的输出
- 来自客户的输出
成功创建套接字
已建立连接
发送数据