服务器正在接受客户端,但未收到任何消息。这是我的服务器代码:
服务器:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string.h>
#include<stdbool.h>
#include<sys/select.h>
#include<errno.h>
//Socket Creation
int socketFile(){
int Socket = socket(AF_INET, SOCK_STREAM, 0);
if(Socket == -1){
perror("Socket Error\n");
exit(1);
}
else
printf("Successfullly Connected to Socket: %d\n",Socket);
return Socket;
}
int bindFile(int Socket, const struct sockaddr * receiver, int len){
int Bind = bind(Socket, receiver, len);
if(Bind == -1){
perror("Bind Error\n");
exit(1);
}
else
printf("Successfullly Connected with Bind number: %d\n", Bind);
}
int listenFile(int Socket, int n){
int listen1 = listen(Socket, n);
if(listen1 == -1){
perror("listen Error\n");
exit(1);
}
else
printf("Successfully Connected with no Listen Error\n");
}
int acceptFile(int Socket, struct sockaddr * receiver, socklen_t addrlen){
int accept1 = accept(Socket, (struct sockaddr *)&receiver, &addrlen);
if(accept1 == -1){
perror("accept Error\n");
exit(1);
}
else
printf("Successfully Accepted with Data Socket number: %d\n", accept1);
}
void clearBuffer(char* b, int len) {
int i;
for (i = 0; i < len; i++)
b[i] = '\0';
sleep(0.1);
}
int main(int abcd, char *args[]) {
//Socket
int Socket = socketFile();
//Struct for Receiver
struct sockaddr_in receiver, sender;
receiver.sin_family = AF_INET;
receiver.sin_port = htons(atoi(args[1]));
receiver.sin_addr.s_addr = inet_addr("127.0.0.1");
int addrlength = sizeof(sender);
socklen_t senderLength;
//Bind
int Bind = bindFile(Socket, (const struct sockaddr *)&receiver, addrlength);
//Listen
int Listen = listenFile(Socket, 5);
char buffer[21];
clearBuffer(buffer, 20);
int message, set = 0, Select, client[30], max_client = 30, i, max_set = Socket;
fd_set readfds, fds;
struct timeval timeout;
for(i = 0; i < max_client; i++){
client[i] = 0;
}
//Clear & Add
FD_ZERO(&fds);
FD_SET(Socket, &fds);
bool stop = false;
while(!stop) {
readfds = fds;
Select = select(max_set +1, &readfds, NULL, NULL, NULL);
if (Select == -1) {
perror("Select");
break;
}
if(FD_ISSET(Socket, &readfds)) {
if(set < max_client) {
client[set] = acceptFile(Socket,(struct sockaddr *) &sender, senderLength);
FD_SET(client[set], &fds);
if(client[set] > max_set)
max_set = client[set];
set++;
}
}
for(i = 0; i < set; i++) {
if(FD_ISSET(client[i], &readfds)){
message = recv(client[i], buffer, 20, 0);
buffer[message] = '\0';
printf("%s\n", buffer);
}
}
}
close(Socket);
return 0;
}
客户端部分还可以,但是连接到服务器并发送第一条消息后,服务器将无法接收该消息。 我在处理错误时遇到很多麻烦。因此,请纠正错误。
答案 0 :(得分:0)
您应该启用所有警告。然后,您会立即看到原因:acceptFile
不返回任何内容,因此client[set]
被设置为垃圾。