Day1
思维导图
作业 实现一下套接字通信
代码
#include<myhead.h>
int main(int argc, const char *argv[])
{
int sfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.s_addr = inet_addr("10.102.145.242");
bind(sfd, (struct sockaddr*)&sin, sizeof(sin));
listen(sfd, 128);
int newfd = accept(sfd, NULL, NULL);
char buf[128] = "";
while(1)
{
bzero(buf, sizeof(buf));
read(newfd, buf, sizeof(buf));
printf("收到客户端消息为:%s\n", buf);
}
close(newfd);
close(sfd);
return 0;
}
#include<myhead.h>
int main(int argc, const char *argv[])
{
int cfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in cin;
cin.sin_family = AF_INET;
cin.sin_port = htons(8888);
cin.sin_addr.s_addr = inet_addr("10.102.145.242");
connect(cfd, (struct sockaddr*)&cin, sizeof(cin));
char buf[128] = "";
while(1)
{
printf("请输入>>>");
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf)-1] = '\0';
write(cfd, buf, sizeof(buf));
printf("发送成功\n");
}
close(cfd);
return 0;
}