思维导图
练习题
1.实现TCP服务器和客户端之间的通信
server.c
#include <myhead.h>
int main(int argc, char const *argv[])
{
//创建套接字
int sfd = socket(AF_INET, SOCK_STREAM, 0);
//端口复用,作用:关闭服务器后再启动不会等待
int reuse = 1;
setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
//填充IP和端口
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(1234);
sin.sin_addr.s_addr = inet_addr("192.168.124.51");
//服务器绑定套接字
bind(sfd, (struct sockaddr *)&sin, sizeof(sin));
//监听客户端是否发送请求
listen(sfd, 128);
//创建用来传递消息的套接字
socklen_t socklen = sizeof(sin);
int newfd = accept(sfd, (struct sockaddr *)&sin, &socklen);
printf("[%s:%d]发来连接请求\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
//消息的发送与接收
char buf[128] = "";
while (1)
{
memset(buf, 0, sizeof(buf));
//接收消息
int res=recv(newfd, buf, sizeof(buf), 0);
if (res == 0)
{
printf("客户端下线\n");
break;
}
printf("[%s:%d] %s\n", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port), buf);
//发送消息
send(newfd, buf, sizeof(buf), 0);
}
//关闭服务器
close(newfd);
close(sfd);
return 0;
}
client.c
#include <myhead.h>
int main(int argc, char const *argv[])
{
//创建套接字
int cfd = socket(AF_INET, SOCK_STREAM, 0);
//填充客户端IP和端口
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(4321);
cin.sin_addr.s_addr = inet_addr("192.168.124.51");
//服务器绑定,也可以不绑定,不绑定客户端端口号随机
bind(cfd, (struct sockaddr *)&cin, sizeof(cin));
//服务器IP和端口
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(1234);
sin.sin_addr.s_addr = inet_addr("192.168.124.51");
//连接服务器,向服务器发送请求
connect(cfd, (struct sockaddr *)&sin, sizeof(sin));
//消息的发送与接收
char buf[128] = "";
while (1)
{
memset(buf, 0, sizeof(buf));
//输入消息
printf("[%s:%d] 请输入--->", inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
//发送消息
send(cfd, buf, sizeof(buf), 0);
//接收消息
recv(cfd, buf, sizeof(buf), 0);
if (strcmp(buf, "q") == 0)
{
printf("下线\n");
break;
}
}
//关闭客户端
close(cfd);
return 0;
}
2.服务器和客户端通信实现客户端控制服务器端机械臂摆动
#include <myhead.h>
#define SER_IP "192.168.124.19"
#define SER_PORT 8888
int main(int argc, char const *argv[])
{
//创建套接字
int cfd = socket(AF_INET, SOCK_STREAM, 0);
//服务器IP和端口
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(1234);
sin.sin_addr.s_addr = inet_addr("192.168.124.19");
//连接服务器,向服务器发送请求
connect(cfd, (struct sockaddr *)&sin, sizeof(sin));
//循环操作,判断w蓝色左 a红色左 s蓝色右 d红色右
char arr[5];
arr[0] = 0xff;
arr[4] = 0xff;
arr[1] = 0x02;
int y = 90;
int y2 = 0;
while (1)
{
memset(arr, 0, sizeof(arr));
//获取终端输入的第一个字符
char key;
scanf(" %c", &key);
switch (key)
{
case 'w':
y++;
arr[2] = 0x01;
arr[3] = y;
//向服务器发送消息
send(cfd, arr, sizeof(arr), 0);
break;
case 's':
y--;
arr[2] = 0x01;
arr[3] = y;
//向服务器发送消息
send(cfd, arr, sizeof(arr), 0);
break;
case 'a':
y2++;
arr[2] = 0x00;
arr[3] = y2;
//向服务器发送消息
send(cfd, arr, sizeof(arr), 0);
break;
case 'd':
y2--;
arr[2] = 0x00;
arr[3] = y2;
//向服务器发送消息
send(cfd, arr, sizeof(arr), 0);
break;
default:
puts("error");
}
}
//关闭客户端
close(cfd);
return 0;
}