我想开发一个使用c应用程序的一些输入的web应用程序,我不知道如何发送和接收两个应用程序之间的消息。Web应用程序和C应用程序之间的通信?Web服务?
我认为web服务是解决方案,但我不知道适合我需求的技术。
任何人都可以提供一些信息或有用的教程吗?
在此先感谢。
我想开发一个使用c应用程序的一些输入的web应用程序,我不知道如何发送和接收两个应用程序之间的消息。Web应用程序和C应用程序之间的通信?Web服务?
我认为web服务是解决方案,但我不知道适合我需求的技术。
任何人都可以提供一些信息或有用的教程吗?
在此先感谢。
您可以使用套接字使用tcp/ip连接。在服务器端写套接字侦听器,在c端写套接字客户端,使用套接字将一些数据发送到服务器。这是简单的例子,如何从客户端发送的东西服务器
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
void cleanup(int sig)
{
printf("\nCleanup on exit\n");
exit(0);
}
int create_socket(uint16_t port)
{
/* Used variables */
int sock;
struct sockaddr_in name;
/* Create the socket. */
sock = socket (AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
perror("socket");
exit(EXIT_FAILURE);
}
/* Give the socket a name. */
name.sin_family = AF_INET;
name.sin_port = htons (port);
name.sin_addr.s_addr = htonl (INADDR_ANY);
/* Connect socket */
if (connect(sock, (struct sockaddr *) &name, sizeof(name)) < 0)
{
perror("Connect");
exit(EXIT_FAILURE);
}
return sock;
}
int send_command(int sock, char *cmd)
{
/* Used variables */
char command[128];
int ret;
/* Null-terminate command */
bzero(command, 128);
/* Create command */
sprintf(command, "%s bla bla \n", cmd);
/* Send */
ret = send(sock, command, strlen(command), 0);
if (ret < 0) return 0;
else printf("Command: %s\n", command);
return 1;
}
int main(int argc, char *argv[])
{
/* Used variables */
int socket, ret;
/* Catch signals */
signal(SIGINT, cleanup);
/* Print usage if there is no given argument */
if (!argv[1])
printf("Usage: %s <command>\n", argv[0]);
/* Create socket with server listener port */
socket = create_socket(5544);
/* Send commant to server */
ret = send_command(socket, argv[1]);
/* Check and print status */
if (ret) printf("Command sent\n");
else printf("Can not send command\n");
return 0;
}
我评论了每一行代码以对您有用
您可以使用网络插座,用于Web应用程序和C应用程序之间的通信。 请参考https://github.com/warmcat/libwebsockets
谢谢你的回答,我会试试看。 有没有办法让服务器询问客户端,然后客户端给出他的答案? – 2015-04-03 11:49:20
是的,客户端可以使用accept()函数接受套接字并从服务器接收数据。 accept()为传入数据返回新的套接字,并且如果将有来自服务器的响应,您可以读取该套接字上的缓冲区。 – 2015-04-03 11:59:28