1. 程式人生 > >C語言實現兩臺電腦通過串列埠通訊

C語言實現兩臺電腦通過串列埠通訊

用C語言實現在傳送端控制檯輸入字串並在接收端接收顯示的功能。

  1. /*********************server.c****************/
  2. #include<stdio.h>
  3. #include<sys/types.h>
  4. #include<sys/stat.h>
  5. #include<fcntl.h>
  6. #include<termios.h>
  7. #define BAUDRATE B38400
  8. #define MODEMDEVICE "/dev/ttyS0"
  9. #define STOP '@'
  10. int main(){  
  11.    int fd,c=0,res;  
  12.    struct
     termios oldtio,newtio;  
  13.    char ch,s1[20];  
  14.    printf("start...\n");  
  15.    fd=open(MODEMDEVICE,O_RDWR | O_NOCTTY);  
  16.    if(fd<0)  
  17.    {  
  18.       perror(MODEMDEVICE);  
  19.       exit(1);  
  20.    }  
  21.    printf("open...\n");  
  22.    tcgetattr(fd,&oldtio);  
  23.    bzero(&newtio,sizeof(newtio));  
  24.    newtio.c_cflag=BAUDRATE|CS8|CLOCAL|CREAD;  
  25.    newtio.c_iflag=IGNPAR;  
  26.    newtio.c_oflag=0;  
  27.    newtio.c_lflag=ICANON;  
  28.    tcflush(fd,TCIFLUSH);  
  29.    tcsetattr(fd,TCSANOW,&newtio);  
  30.    printf("writing...\n");  
  31.    while(1)  
  32.    {  
  33.       while((ch=getchar())!='@')  
  34.         {  
  35.            s1[0]=ch;  
  36.            res=write(fd,s1,1);  
  37.         }  
  38.         s1[0]=ch;  
  39.         s1[1]='\n';  
  40.         res=write(fd,s1,2);  
  41.         break;  
  42.    }  
  43.    printf("close...\n");  
  44.    close(fd);  
  45.    tcsetattr(fd,TCSANOW,&oldtio);  
  46.    return 0;  

  1. /**************client.c***************/
  2. #include<stdio.h>
  3. #include<sys/types.h>
  4. #include<fcntl.h>
  5. #include<termios.h>
  6. #define BAUDRATE B38400
  7. #define MODEMDEVICE "/dev/ttyS0"
  8. int main()  
  9. {  
  10.     int fd,c=0,res;  
  11.     struct termios oldtio,newtio;  
  12.     char buf[256];  
  13.     printf("start ...\n");  
  14.     fd=open(MODEMDEVICE,O_RDWR | O_NOCTTY);  
  15.     if(fd<0)  
  16.     {  
  17.       perror(MODEMDEVICE);  
  18.       exit(1);  
  19.     }  
  20.     printf("open...\n");  
  21.     tcgetattr(fd,&oldtio);  
  22.     bzero(&newtio,sizeof(newtio));  
  23.     newtio.c_cflag=BAUDRATE | CS8 | CLOCAL | CREAD;  
  24.     newtio.c_iflag=IGNPAR;  
  25.     newtio.c_oflag=0;  
  26.     newtio.c_lflag=ICANON;  
  27.     tcflush(fd,TCIFLUSH);  
  28.     tcsetattr(fd,TCSANOW,&newtio);  
  29.     printf("reading...\n");  
  30.     while(1)  
  31.     {  
  32.        res=read(fd,buf,255);  
  33.        buf[res]=0;  
  34.        printf("res=%d vuf=%s\n",res,buf);  
  35.        if(buf[0]=='a'break;  
  36.     }  
  37.        printf("close...\n");  
  38.        close(fd);  
  39.        tcsetattr(fd,TCSANOW,&oldtio);  
  40.        return 0;  
  41. }  

傳送端截圖:

接受端截圖:


(-----------that's all-----------)