服务器
#include <myhead.h>
#define SPORT 8888
#define SIP "192.168.0.129"
#define BACKLOG 10
int main(int argc, const char *argv[])
{
//1.通过套接字获取文件描述符
int oldfd = socket(AF_INET,SOCK_STREAM,0);
if(oldfd == -1){
perror("socket");
return -1;
}
printf("套接字获取成功\n");
struct sockaddr_in sin = {
.sin_family = AF_INET,
.sin_port = htons(SPORT),
.sin_addr.s_addr = inet_addr(SIP)
};
//2.绑定
if(bind(oldfd,(struct sockaddr *)&sin,sizeof(sin))==-1){
perror("bind");
return -1;
}
printf("绑定成功\n");
printf("监听成功\n");
//3.接收信息
struct sockaddr_in cin;
socklen_t cinlen = sizeof(cin);
int newfd = accept(oldfd,(struct sockaddr *)&cin,&cinlen);
if(newfd == -1){
perror("accept");
return -1;
}
printf("连接成功\n");
char buff[100];
while(1){
memset(buff,0,sizeof(buff));
int len = recv(newfd,buff,sizeof(buff),0);
printf("读取的信息:%s\n",buff);
if(len == 0){
printf("客户端断开连接\n");
break;
}
printf("请输入发送给客户端的信息:");
fgets(buff,sizeof(buff),stdin);
buff[strlen(buff)-1] = '\0';
if(strcmp(buff,"quit")==0){
break;
}
send(newfd,buff,sizeof(buff),0);
}
close(oldfd);
close(newfd);
return 0;
}
客户端
ubuntu@ubuntu:cs$ cat 7.c
#include <myhead.h>
#define CLPORT 8888
#define CLIP "192.168.0.129"
int main(int argc, const char *argv[])
{
int oldfd = socket(AF_INET,SOCK_STREAM,0);
if(oldfd == -1){
perror("socket");
return -1;
}
struct sockaddr_in cin = {
.sin_family = AF_INET,
.sin_port = htons(CLPORT),
.sin_addr.s_addr = inet_addr(CLIP)
};
if(connect(oldfd,(struct sockaddr *)&cin,sizeof(cin))==-1){
perror("connect");
return -1;
}
printf("连接服务器成功\n");
char buff[100];
while(1){
memset(buff,0,sizeof(buff));
printf("输入发送给服务器的消息:");
fgets(buff,sizeof(buff),stdin);
buff[strlen(buff)-1] = '\0';
if(strcmp(buff,"quit")==0){
break;
}
send(oldfd,buff,sizeof(buff),0);
memset(buff,0,sizeof(buff));
recv(oldfd,buff,sizeof(buff),0);
printf("接收到的服务器信息:%s\n",buff);
}
close(oldfd);
return 0;
}