TCP传输控制协议
向用户进程提供可靠的全双工字节流(字节流:给每一个字节编序)
UDP用户数据报协议
是一种无连接的协议
获取时间服务的客户端
client
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <fcntl.h>
#include <arpa/inet.h>
int main(int argc,char *argv[])
{
int sockfd;
struct sockaddr_in servaddr;
char buf[100];//存储读取的内容
int bytes;//存储读取的字节数
if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0)//创建套接字
{
printf("socket error\n");
return -1;
}
//结构体中成员变量初始化为0
bzero(&servaddr,sizeof(servaddr));
//初始化成员变量
servaddr.sin_family = AF_INET;//IPv4
servaddr.sin_addr.s_addr = inet_addr("192.168.1.12");//转换为地址格式
servaddr.sin_port = htons(8888);//主机序转换到网络序
//连接服务器
if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) < 0)//绑定服务器ip和端口到>套结字
{
perror("connect error");
return -2;
}
//存储读取的数据和读取的字节数
bytes = read(sockfd,buf,100);
if(bytes < 0)
{
printf("Error ,read failed\n");
close(sockfd);
return -3;
}
//如果读取的字节数为0 ,就说明连接已经关闭了
if(0 == bytes)
{
printf("Server close connection\n");
close(sockfd);
return -4;
}
//打印读取的字节数和读取的内容
printf("read bytes %d\n",bytes);
printf("Time: %s\n",buf);
//关闭套结字
close(sockfd);
return 0;
}
运行结果
read bytes 25
Time: Tue Jul 21 14:45:10 2020
server
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>