客户端:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SIZE 100
#define IP "127.0.0.1"
#define PORT 10086
int main()
{
int socketID = 0;
int addrLength = 0;
int ret = 0;
struct sockaddr_in addr;
char buf[SIZE] = {"you are super man!"};
//创建套接字
socketID = socket(AF_INET, SOCK_STREAM, 0);
if (socketID < 0)
{
perror("socket error");
return -1;
}
printf("socket ok %d\r\n", socketID);
//设置对方的地址
addrLength = sizeof(addr);
memset(&addr, 0, addrLength);
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = inet_addr(IP);
//发送连接请求 connect()
ret = connect(socketID, (struct sockaddr *)&addr, addrLength);
if (ret < 0)
{
perror("connect error");
close(socketID);
return -1;
}
printf("connect ok\r\n");
//通信 (发、收消息)write() read()
ret = write(socketID, buf, strlen(buf));
if (ret > 0)
{
printf("client send data success\r\n");
}
memset(buf, 0, SIZE);
ret = read(socketID, buf, SIZE - 1);
if (ret > 0)
{
printf("client get : %s\r\n", buf);
}
//关闭套接字 close()
close(socketID);
return 0;
}
服务器:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SIZE 100
#define IP "127.0.0.1"
#define PORT 10086
int main()
{
int socketID = 0;
int ret = 0;
int addrLength = 0;
int newID = 0;
struct sockaddr_in addr;
char buf[SIZE] = {0};
//创建套接字
socketID = socket(AF_INET, SOCK_STREAM, 0);
if (socketID < 0)
{
perror("socket error");
return -1;
}
printf("socket ok, %d\r\n", socketID);
//绑定自己的地址
addrLength = sizeof(addr);
memset(&addr, 0, addrLength);
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = INADDR_ANY;
ret = bind(socketID, (struct sockaddr *)&addr, addrLength);
if (ret < 0)
{
perror("bind error");
close(socketID);
return -1;
}
printf("bind ok\r\n");
//监听
listen(socketID, 5);
printf("listen ok\r\n");
//接受连接
newID = accept(socketID, (struct sockaddr *)&addr, &addrLength);
if (newID < 0)
{
perror("accept error");
close(socketID);
return -1;
}
printf("accept ok, %d\r\n", newID);
//通信
//ret = read(newID, buf, SIZE - 1);
ret = recv(newID, buf, SIZE - 1, 0);
if (ret > 0)
{
printf("server get :%s\r\n", buf);
}
memset(buf, 0, SIZE);
fgets(buf, SIZE - 1, stdin);
//ret = write(newID, buf, strlen(buf));
ret = send(newID, buf, strlen(buf), 0);
if (ret > 0)
{
printf("server send ok\r\n");
}
//关闭套接字
close(newID);
close(socketID);
return 0;
}
协议的特点*
传输层协议:TCP、UDP
TCP特点:
建立连接、消息可靠性高、速度慢
流式套接字
UDP特点:
不需要建立连接、消息可靠性差、速度快
用户数据报套接字
. TCP通信流程*
客户端 服务器端
创建套接字–(协议) 创建套接字–(协议)
设置对方的地址(IP&&PORT) 绑定自己的地址(IP && PORT)
监听
发送连接请求 接受连接请求
通信(收、发消息) 通信(发、收消息)
关闭套接字 关闭套接字