客户端:
描 述:由该客户端先向服务器发送信息,待服务器接收并发送过来后才能接着发第二条,当接收的信息为“quit”时结束对话
================================================*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
char buf[64] = {0};
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd == -1)
{
perror("socket");
return -1;
}
struct sockaddr_in saddr; //服务器的ip和port
bzero(&saddr, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6666);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
printf("自己:");
do
{
fgets(buf, 64, stdin); //由键盘输入信息
int ret = sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&saddr, sizeof(saddr)); //发送数据
if(ret == -1)
{
perror("sendto");
break;
}
bzero(buf, sizeof(buf));
ret = recvfrom(sockfd, buf, sizeof(buf), 0, NULL, NULL); //接收服务器发来的信息
if(ret == -1)
{
perror("recvfrom");
break;
}
printf("\n对方:%s", buf); //打印服务器发来的信息
if(strncmp(buf, "quit", 4) != 0) //这里为了结束后的规范设置的一个判断
{
printf("\n自己:");
}
}while(strncmp(buf, "quit", 4) != 0); //当服务器发来的信息为“quit”时结束循环
close(sockfd);
return 0;
}
服务器:
描 述:由客户端先发送指令,接收后才能发过去,当键盘输入“quit”时结束会话
================================================*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
char buf[64] = {0};
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd == -1)
{
perror("socket");
return -1;
}
struct sockaddr_in saddr; //服务器的ip和port
bzero(&saddr, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6666);
saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
int ret = bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr));
if(ret == -1)
{
perror("bind");
close(sockfd);
return -1;
}
struct sockaddr_in addr; //接收方的信息
bzero(&addr, sizeof(addr));
socklen_t len = sizeof(addr);
do
{
bzero(buf, sizeof(buf));
ret = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&addr, &len); //接受数据
if(ret == -1)
{
perror("recvfrom");
close(sockfd);
return -1;
}
printf("对方:%s\n自己:", buf); //打印客户端发来的信息,并为下一步自己发送信息做注释
fgets(buf, 64, stdin); //从键盘输入信息
ret = sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&addr, sizeof(addr));
if(ret == -1)
{
perror("sendto");
close(sockfd);
return -1;
}
if(strncmp(buf, "quit", 4) != 0) //为了间隔规范做注释
{
printf("\n");
}
}while(strncmp(buf, "quit", 4) != 0); //当键盘输入“quit”时结束循环
close(sockfd);
return 0;
}
1、由该客户端先向服务器发送信息,待服务器接收并发送过来后才能接着发第二条,当接收的信息为“quit”时结束对话;
2、由客户端先发送指令,接收后才能发过去,当键盘输入“quit”时结束会话;