libsocket的行为创建\u inet\u服务器\u socket和接受\u inet\u流\u socket
我正在编写一个小型C服务器来接收来自ESP8266模块(小型无线模块)的数据。具体来说,我很好奇我应该检查什么来寻找连接。这是我的密码:libsocket的行为创建\u inet\u服务器\u socket和接受\u inet\u流\u socket,c,multithreading,sockets,server,C,Multithreading,Sockets,Server,我正在编写一个小型C服务器来接收来自ESP8266模块(小型无线模块)的数据。具体来说,我很好奇我应该检查什么来寻找连接。这是我的密码: /* * main.c * * Created on: Sep 9, 2015 * Author: matthew */ #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.
/*
* main.c
*
* Created on: Sep 9, 2015
* Author: matthew
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <libsocket/libinetsocket.h>
#include <pthread.h>
int* async_socket_rcv(int clientfd);
int main(int argc, char *argv[])
{
int socketfd, clientfd;
pthread_t thread;
socketfd = create_inet_server_socket("0.0.0.0", "5677", LIBSOCKET_TCP, LIBSOCKET_IPv4, 0);
while(1)
{
clientfd = accept_inet_stream_socket(socketfd,0,0,0,0,0,0);
if(clientfd >= 0 ){
pthread_create(&thread, NULL, async_socket_rcv, clientfd);
}
}
}
int* async_socket_rcv(int clientfd)
{
char* buf = calloc(16,1);
pthread_t thread_id = pthread_self();
printf("Thread created");
while(clientfd > 0){
read(clientfd, buf, 15);
printf("%s\n", buf);
}
close(clientfd);
return 0;
}
/*
*main.c
*
*创建日期:2015年9月9日
*作者:马修
*/
#包括
#包括
#包括
#包括
#包括
#包括
int*异步套接字rcv(int clientfd);
int main(int argc,char*argv[])
{
int socketfd,clientfd;
pthread\u t线程;
socketfd=create_inet_server_socket(“0.0.0.0”,“5677”,LIBSOCKET_TCP,LIBSOCKET_IPv4,0);
而(1)
{
clientfd=accept_inet_stream_socket(socketfd,0,0,0,0);
如果(clientfd>=0){
pthread_create(&thread,NULL,async_socket_rcv,clientfd);
}
}
}
int*async\u socket\u rcv(int clientfd)
{
char*buf=calloc(16,1);
pthread_t thread_id=pthread_self();
printf(“线程创建”);
而(clientfd>0){
读(clientfd,buf,15);
printf(“%s\n”,buf);
}
关闭(clientfd);
返回0;
}
如您所见,我目前正在查看accept_inet_stream_套接字是否返回错误以外的任何内容,但这似乎只有在通过已建立的连接发送数据时才起作用。我希望我的代码在建立连接后立即启动一个线程,并将连接的所有处理交给该线程,而不管是否发送了数据
我的情况不清楚,让我来解释一下
目前正在发生的情况:
启动服务器>连接到服务器>什么都不发生>向服务器发送字符串>服务器输出“线程已启动”和已发送的字符串
我想要的是:
启动服务器>连接到服务器>服务器显示“线程已启动”>向服务器发送字符串>服务器输出发送的字符串
另外,如果你们看到任何明显的错误或不合逻辑的事情,请检查我的代码并告诉我。我正在同时学习套接字和线程:)
仅供参考,在发布之前,我搜索了大量的答案,即:您的编译器没有抱怨您要传递给
pthread\u create()
的函数指针的函数原型明显不正确吗?没有。。有什么问题吗?manpthread\u create:intpthread\u create(pthread\u t*thread,constpthread\u attr\u t*attr,void*(*start\u例程)(void*),void*arg)代码>。传递给pthread\u create()
的函数不应将int
作为参数。提示:如果将setvbuf(stdout,0,_IONBF,0)
添加到main()
的开头,您的问题将奇迹般地消失……您是在谈论异步套接字的返回类型吗?另外,setvbuf用于在等待连接时启用阻塞?