http服务端接口实例 c#post
时间: 2023-09-06 21:03:20 浏览: 89
C#实现Http post方式 服务端+客户端源码
HTTP服务端接口是一种通过HTTP协议提供服务的程序接口。下面是一个HTTP服务端接口的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
int sockfd, newsockfd, portno, clilen;
char buffer[1024];
struct sockaddr_in serv_addr, cli_addr;
int n;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
return 1;
}
memset((char *) &serv_addr, 0, sizeof(serv_addr));
portno = 8080;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR on binding");
return 1;
}
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) {
perror("ERROR on accept");
return 1;
}
memset(buffer, 0, 1024);
n = read(newsockfd, buffer, 1023);
if (n < 0) {
perror("ERROR reading from socket");
return 1;
}
printf("Here is the message: %s\n", buffer);
n = write(newsockfd, "I got your message", sizeof("I got your message"));
if (n < 0) {
perror("ERROR writing to socket");
return 1;
}
close(newsockfd);
close(sockfd);
return 0;
}
```
上述代码实现了一个简单的HTTP服务端接口。它监听8080端口,接收来自客户端的HTTP请求,返回一个固定的响应消息"I got your message",并将客户端发送的消息打印输出。
阅读全文