基于TCP协议的通信模型
(1)創建socket,使用socket函數
(2)準備通信地址,使用結構體類型
(3)綁定socket和通信地址,使用bind函數
(4)進行監聽,使用listen函數
(5)響應客戶端的連接請求,使用accept函數
(6)進行通信,使用read/write函數
(7)關閉socket,使用close函數
例子:
//基于socket的本地通信
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
int main()
{
//1.創建socket,使用socket函數
int sockfd=socket(AF_UNIX,SOCK_DGRAM,0);//本地通信/數據報
if(-1==sockfd)
{
perror("socket"),exit(-1);
}
printf("創建socket成功\n");
//2.準備通信地址,使用結構體類型
struct sockaddr_un addr;
addr.sun_family=AF_UNIX;
strcpy(addr.sun_path,"a.sock");
//3.綁定socket和通信地址,使用bind函數
int res=bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
if(-1==res)
{
perror("bind"),exit(-1);
}
printf("綁定成功\n");
//4.進行通信,使用read/write函數
char buf[100]={0};
res=read(sockfd,buf,sizeof(buf));
if(-1==res)
{
perror("read"),exit(-1);
}
printf("讀取客戶端發來的數據是:%s,數據大小是:%d\n",buf,res);
//5.關閉socket,使用close函數
close(sockfd);
return 0;
}
(1)創建socket,使用socket函數
(2)準備通信地址,使用結構體類型(服務器的地址)
(3)連接socket和通信地址,使用connect函數
(4)進行讀寫操作,使用read/write函數
(5)關閉socket,使用close函數
例子:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <string.h>
int main()
{
//1.創建socket,使用socket函數
int sockfd=socket(AF_UNIX,SOCK_DGRAM,0);//本地通信/數據報
if(-1==sockfd)
{
perror("socket"),exit(-1);
}
printf("創建socket成功");
//2.準備通信地址,使用結構體類型
struct sockaddr_un addr;
addr.sun_family=AF_UNIX;
strcpy(addr.sun_path,"a.sock");
//3.綁定socket和通信地址,使用connect函數
int res=connect(sockfd,(struct sockaddr*)&addr,sizeof(addr));
if(-1==res)
{
perror("connect"),exit(-1);
}
printf("連接服務器成功\n");
//4.進行通信,使用write函數
res=write(sockfd,"hello",5);
if(-1==res)
{
perror("write"),exit(-1);
}
printf("發送給服務器的數據成功,數據大小是:%d\n",res);
//5.關閉socket,使用close函數
close(sockfd);
return 0;
}
總結
以上是生活随笔為你收集整理的基于TCP协议的通信模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JMS学习三(ActiveMQ消息的可靠
- 下一篇: 安装head插件依赖包grunt-cli