我正在尝试查看对套接字服务器的HTTP请求。当我从浏览器请求此服务器时,响应自然是无效的,因为此处没有HTTP响应。但是我想在我的终端屏幕上看到这个HTTP请求。任何想法,我该怎么办?
这只是多用途套接字服务器代码:
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *((int*)socket_desc);
char *message = "Greetings! I am your connection handler\n";;
//Send some messages to the client
write(sock , message , strlen(message));
message = "Its my duty to communicate with you";
write(sock , message , strlen(message));
free(socket_desc); //Free the socket pointer
return 0;
}
int main(int argc, char *argv[])
{
int socket_desc, new_socket, c, *new_sock;
struct sockaddr_in server, client;
char *message;
socket_desc = socket(AF_INET , SOCK_STREAM , 0);
if (socket_desc == -1)
{
puts("Could not create socket");
return 1;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(8888);
if(bind(socket_desc, (struct sockaddr *)&server, sizeof(server)) < 0)
{
puts("Binding failed");
return 1;
}
listen(socket_desc, 3);
puts("Waiting for incoming connections...");
c = sizeof(struct sockaddr_in);
while((new_socket =
accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
{
puts("Connection accepted");
message = "Hello Client, I will assign a handler for you\n";
write(new_socket, message, strlen(message));
pthread_t sniffer_thread;
new_sock = malloc(1); // a memory allocator
*new_sock = new_socket;
if(pthread_create(&sniffer_thread, NULL, connection_handler,
(void*)new_sock) < 0)
{
puts("Could not create thread");
return 1;
}
puts("Handler assigned");
}
return 0;
}