📄 chuanwangshou.c
字号:
#include <stdio.h>#include <sys/ioctl.h>#include <termios.h>#include <stdlib.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>#include <netdb.h>#include <sys/stat.h>#include <fcntl.h>#include <signal.h>#include <sys/time.h>#include <pthread.h>
#include <string.h>struct termios tio;int fd; char buff[100];int len;int i;void chuankou(){ if((fd = open("/dev/ttyS0",O_RDWR |O_NDELAY |O_NOCTTY))<0) { printf("Couldn't open\n"); exit(1); } else { printf("comm open success!\n"); } tio.c_cflag = B115200 |CS8 |CREAD | CLOCAL; tio.c_cflag &=~HUPCL; tio.c_lflag = 0; tio.c_iflag = IGNPAR; tio.c_oflag = 0; tio.c_cc[VTIME] = 0; tio.c_cc[VMIN] = 0; tcflush(fd,TCIFLUSH); tcsetattr(fd,TCSANOW,&tio); fcntl(fd,F_SETFL,FNDELAY); while(1) { len = read(fd,buff,8); if(len > 0) { for(i=0; i<len; i++) printf("%c",buff[i]); printf("\n"); } sleep(1);}close(fd);}void server()
{
int listensock,connsock; //定义两个socket套接字,一个用于监听,一个用于通讯
struct sockaddr_in serveraddr; //定义网络套接字地址结构
//定义要发送的数据缓冲区;
listensock = socket(AF_INET,SOCK_STREAM,0); //创建一个套接字,用于监听
bzero(&serveraddr,sizeof(serveraddr)); //地址结构清零
serveraddr.sin_family = AF_INET; //指定使用的通讯协议族
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
//指定接受任何连接,因为服务器不知道谁会要求连接
serveraddr.sin_port = htons(5000); //指定监听的端口
bind(listensock,(struct sockaddr *)&serveraddr,sizeof(serveraddr)); //给套接口邦定地址
listen(listensock,1024); //开始监听
connsock = accept(listensock,(struct sockaddr *)NULL, NULL);
//建立通讯的套接字,accept函数,等待客户端程序使用connect函数的连接
while(1) { send(connsock,buff,sizeof(buff), 0);//向客户端发送数据
} close(connsock); //关闭通讯套接字
close(listensock); //关闭监听套接字 }void main(){ pthread_t id; pthread_create(&id,NULL,(void *)chuankou,NULL); pthread_create(&id,NULL,(void *)server,NULL); while(1) { sleep(1); } }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -