在套接字应用程序中接受 getch() maneer 中的按键的正确方法是什么?我花了很多天试图解决这个问题,我发现的只是使用各种 IAC 序列将 telnet 客户端置于字符模式,但是当我这样做时,我的应用程序不会等待用户输入,看起来就像跳过 read()。这是我的代码:
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <time.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0;
struct sockaddr_in serv_addr, cli_addr;
int clilen;
char sendBuff[1025];
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000); // listen on port 5000
bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
listen(listenfd, 10);
clilen=sizeof(cli_addr);
while(1)
{
connfd = accept(listenfd, (struct sockaddr*) &cli_addr, &clilen);
char mystring[4096];
strcpy(mystring,"\377\375\003"); // IAC DO SUPPRESS GO AHEAD, put telnet client into character mode
write(connfd, mystring, strlen(mystring));
char bafer[4096];
strcpy(mystring,"\033[2J\033[H"); // clear screen, move cursor to upper left corner
write(connfd, mystring, strlen(mystring));
strcpy(mystring,"\033[31;7m"); // red letters
write(connfd, mystring, strlen(mystring));
strcpy(mystring,"\033[0m"); // reset VT100 colors
write(connfd, mystring, strlen(mystring));
strcpy(mystring,"Enter key: ");
write (connfd, mystring, strlen(mystring));
read (connfd, bafer, 4095);
strcpy(mystring, "You pressed: ");
write (connfd, mystring, strlen(mystring));
write(connfd, bafer, strlen(bafer));
close(connfd);
sleep(1);
}
}