我正在 linux 中编写一个服务器客户端聊天程序。由于某种原因,该代码无法按预期工作。
问题出在客户端代码中,在 while 循环内,doesn't wait at scanf
用于获取输入的编译器,而不是它sends some garbage data itself to the server
,作为回报,服务器也发送了一些数据和client program terminates
.
由于我的知识有限,我无法弄清楚问题,您的帮助将不胜感激。
服务器.c
#define PORT 3690
#define MaxBufferLength 1024
int main()
{
int sockFd, bytesRead, bytesSent;
char buffer[MaxBufferLength];
struct sockaddr_in server, client;
server.sin_port= htons(PORT);
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
sockFd = socket(AF_INET, SOCK_STREAM, 0);
if(sockFd == -1)
printf("Unable to open socket\n");
int i = bind(sockFd, (struct sockaddr *) &server, sizeof(struct sockaddr));
if(i == -1)
perror("Unable to bind\n");
i = listen(sockFd, 1);
if(i == -1)
printf("Unable to listen\n");
int connectionSocket = accept(sockFd, (struct sockaddr *) &client, sizeof(struct sockaddr));
if(connectionSocket == 1)
printf("connection established\n");
while(1)
{
bytesRead = recv(connectionSocket, buffer, MaxBufferLength, 0);
buffer[bytesRead] = '\0';
printf("Client said: \n %s\n", buffer);
scanf("\n\n = %s", buffer);
bytesSent = send(connectionSocket, buffer, strlen(buffer), 0);
if(bytesSent == -1)
perror("Failed to send a message");
connectionSocket = accept(sockFd, (struct sockaddr *) &client, sizeof(struct sockaddr)); // wait for connection again
}
close(sockFd);
return 0;
}
问候