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