我正在編寫一個簡單的客戶端/服務器應用程序,並且無法使客戶端持續響應(此刻爲回顯)發送給它的消息。使客戶端不斷響應來自服務器的消息
client.c
#define BUF_SIZE 1024
int ctrlsockfd;
void error(const char *message);
void closeStreams();
void writeResponse(const char *message);
int main (int argc, const char *argv[]) {
printf("Client\n");
// Connection code snipped
// Handle responses
int bytes_read;
char buffer[BUF_SIZE];
while (1) {
// Fetch a message
bytes_read = read(ctrlsockfd, buffer, BUF_SIZE);
if (bytes_read == -1) {
error("Failed to read");
}
// Send it back
if (write(ctrlsockfd, buffer, strlen(buffer) + 1) == -1) {
error("Failed to write");
}
}
// Disconnect
closeStreams();
return 0;
}
host.c
#define BUF_SIZE 1024
#define LISTENPORT 9735
void closeStreams();
void error(const char *message);
int ctrlsockfd, clientsockfd;
int main (int argc, const char *argv[]) {
printf("Server\n");
// Connection code snipped
// Accept a request (blocking) - we can only connect to one client at a time
clientlen = sizeof(clientaddr);
clientsockfd = accept(ctrlsockfd, (struct sockaddr *) &clientaddr, (socklen_t*) &clientlen);
if (clientsockfd == -1) {
error("Error accepting");
}
while (1) {
// Read input string from stdin
printf("> ");
char message[BUF_SIZE];
if (scanf("%s", message) == -1) {
error("Failed to read from terminal");
}
// Send to client
if (write(clientsockfd, message, strlen(message) + 1) == -1) {
error("Failed to send message");
} else {
printf("Sent message %s\n", message);
}
// Read response from client
char response[BUF_SIZE];
if (read(clientsockfd, response, BUF_SIZE) == -1) {
error("Error reading response");
} else {
printf("Response: %s\n", response);
}
// Close the connection
closeStreams();
}
}
這裏有什麼問題嗎?
是,在我的情況下,我需要扭轉角色,這樣你纔可以切換名稱 - 我也只需要聽一個客戶端的請求。 – Ross 2011-04-24 12:10:51
@Ross - 還好,請注意,如果您想繼續發送數據,請關閉服務器迴路末端的連接,否則不應關閉連接。 – MByD 2011-04-24 12:12:34
啊,那就是問題所在 - 感謝您的幫助(以及其他問題)! – Ross 2011-04-24 12:14:25