我正在尝试创建一个简单的服务器,以便两个客户端可以相互通信。主服务器代码接受两个客户端连接,然后分叉使用execl在两个客户端之间生成个人服务器的进程,以便主服务器可以继续查找新连接。一切似乎工作正常,直到个人服务器试图联系客户,他们都收到胡言乱语,如果有人知道可能导致这种情况,请告诉我。
接受两个客户端后的主服务器:
if(fork() == 0){
close(listener);
int nBytes;
char* playerOne[20];
char* playerTwo[20];
//Creates strings to hold file descriptor information for execl
char connAscii[sizeof(int)];
char connAscii2[sizeof(int)];
snprintf(connAscii,sizeof(conn), "%d", conn);
snprintf(connAscii2,sizeof(conn2), "%d", conn2);
fprintf(stderr, "Int conn: %d, asciiConn: %s, backToInt: %d\n", conn, connAscii, atoi(connAscii));
char *argf[2];
argf[0] = connAscii;
argf[1] = connAscii2;
fprintf(stderr, "that is to say %s and %s\n", argf[0], argf[1]);
//Send Handle Request to Connection 1
nBytes = send(conn, handleRequest, sizeof(handleRequest),0);
if(nBytes == -1){
perror("send");
exit(1);
}
//Receive Handle from Connection 1
nBytes = recv(conn, playerOne, 20, 0);
if(nBytes == -1){
perror("recv");
exit(1);
}
//Send Handle Request to Connection 2
nBytes = send(conn2, handleRequest, sizeof(handleRequest),0);
if(nBytes == -1){
perror("send");
exit(1);
}
//Receive Handle from Connection 2
nBytes = recv(conn2, playerTwo, 20, 0);
if(nBytes == -1){
perror("recv");
exit(1);
}
//Send Handle for Connection 2 to Connection 1
nBytes = send(conn, playerTwo, sizeof(playerTwo),0);
if(nBytes == -1){
perror("send");
exit(1);
}
//Send Handle for Connection 1 to Connection 2
nBytes = send(conn2, playerOne, sizeof(playerOne),0);
if(nBytes == -1){
perror("send");
exit(1);
}
//Passes file descriptors to privateServer
execl("privateServer","privateServer", connAscii, connAscii2, (char *)0);
}
execl:
调用的个人服务器char greet[] = {"Hello players, please wait for match setup."};
int main(int argc, char *argv[]) {
int conn1 = atoi(argv[1]);
int conn2 = atoi(argv[2]);
int sent;
fprintf(stderr, "Attempting connection with %d\n", conn1);
sent = send(conn1, greet,sizeof(greet),0);
if(sent == -1){
perror("send");
exit(1);
}
sent = send(conn2, greet,sizeof(greet),0);
if(sent == -1){
perror("send");
exit(1);
}
fprintf(stderr,"Hopefully they got it\n");
return 0;
}
客户端:通过char读取recv buff char导致乱码并打印整个缓冲区并不显示任何内容,但numbytes == 61。
char *buff = (char*)malloc(100);
memset(&buff[0],0,sizeof(buff));
numbytes = recv(sockfd, buff, 99, 0); //should be from private server
if (numbytes == -1) {
perror("recv");
exit(1);
}
buff[numbytes] = '\0';
int i;
for(i = 0; i < numbytes; i++){
fprintf(stderr, "%c", buff[i]);
}
printf("From match server: %.*s (%d bytes)\n", numbytes, buff, numbytes);
答案 0 :(得分:1)
有几个错误:
char* playerOne[20];
char* playerTwo[20];
你想要一个字符数组,而不是一个指向字符的指针数组
更改为
char playerOne[20];
char playerTwo[20];
在这里:
char *buff = (char*)malloc(100);
memset(&buff[0],0,sizeof(buff));
sizeof(buff)
是指向char
的指针的大小,更改为
memset(&buff[0],0,100);
正如@ user3629249所指出的,不要使用像100这样的幻数
#define MAX_BUFF 100
char *buff = malloc(MAX_BUFF);
memset(&buff[0],0,MAX_BUFF);
但是如果你是以null结尾字符串,则不需要memset
。