相关函数
(1)socket()函数
int socket(int domain, int type, int protocol);
(2)bind()函数: IP号端口号与相应描述字赋值函数
int bind(int sockfd, const struct sockaddr *addr,socklen t addrlen);
(3)listen()函数:监听设置函数
int listen(int sockfd, int backlog);
(4)accept()函数
int accept(int sockfd, struct sockaddr *addr, socklen t *addrlen);
先写服务端代码:
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char **argv)
{
int s_fd;
int c_fd;
int n_read;
char readBuf[128];
char msg[128] = {0};
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
if(argc != 3)
{
printf("param is not good\n");
exit(-1);
}
memset(&s_addr,0,sizeof(struct sockaddr_in));
memset(&c_addr,0,sizeof(struct sockaddr_in));
//1.socket
s_fd = socket(AF_INET,SOCK_STREAM,0);
if(s_fd == -1)
{
perror("socket");
exit(-1);
}
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(atoi(argv[2]));
inet_aton(argv[1],&s_addr.sin_addr);
//2.bind
bind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));
//3.listen
listen(s_fd,10);
//4.accept
int clen = sizeof(struct sockaddr_in);
while(1)
{
c_fd = accept(s_fd,(struct sockaddr *)&c_addr,&clen);
if(c_fd == -1)
{
perror("accept");
}
printf("get connect:%s\n",inet_ntoa(c_addr.sin_addr));
if(fork() == 0)
{
if(fork() == 0)
{
while(1)
{
memset(msg,0,sizeof(msg));
printf("input:");
gets(msg);
write(c_fd,msg,strlen(msg));
}
}
//5.read
while(1)
{
memset(readBuf,0,sizeof(readBuf));
n_read = read(c_fd,readBuf,128);
if(n_read == -1)
{
perror("read");
}
else
{
printf("get message:%d,%s\n",n_read,readBuf);
}
}
break;
}
}
return 0;
}
再写客户端代码:
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char **argv)
{
int c_fd;
int n_read;
char readBuf[128];
// char *msg = "msg form client";
char msg[128] = {0};
struct sockaddr_in c_addr;
memset(&c_addr,0,sizeof(struct sockaddr_in));
if(argc != 3)
{
printf("parm is not good\n");
exit(-1);
}
//1.socket
c_fd = socket(AF_INET,SOCK_STREAM,0);
if(c_fd == -1)
{
perror("socket");
exit(-1);
}
c_addr.sin_family = AF_INET;
c_addr.sin_port = htons(atoi(argv[2]));
inet_aton(argv[1],&c_addr.sin_addr);
//2.connect
if(connect(c_fd,(struct sockaddr *)&c_addr,sizeof(struct sockaddr)) == -1)
{
perror("connect");
exit(-1);
}
while(1)
{
if(fork() == 0)
{
while(1)
{
memset(msg,0,sizeof(msg));
printf("input:");
gets(msg);
write(c_fd,msg,strlen(msg));
}
}
while(1)
{
memset(readBuf,0,sizeof(readBuf));
n_read = read(c_fd,readBuf,128);
if(n_read == -1)
{
perror("read");
}
else
{
printf("get message form server:%d,%s\n",n_read,readBuf);
}
}
}
return 0;
}
编译结果:
实现了双方聊天