1、服务器端代码
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<string.h>
#include<netinet/in.h>
int startup(const char *_ip,int _port)
{
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0){
perror("socket");
exit(1);
}
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(_port);
local.sin_addr.s_addr = inet_addr(_ip);
socklen_t lenth = sizeof(local);
int opt = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
if(bind(sock,(struct sockaddr*)&local,lenth) < 0){
perror("bind");
exit(2);
}
if(listen(sock,10) < 0){
perror("listen");
exit(3);
}
return sock;
}
static void usage(const char* proc)
{
printf("[local_ip] [local_port]\n",proc);
}
int main(int argc,char *argv[])
{
if(argc != 3){
usage(argv[0]);
return 1;
}
int listen_sock = startup(argv[1],atoi(argv[2]));
struct sockaddr_in client;
socklen_t len = sizeof(client);
while(1){
int new_sock = accept(listen_sock,(struct sockaddr*)&client,&len);
if(new_sock < 0){
perror("new_sock");
exit(0);
}else{
pid_t id = fork();
if(id == 0){//child
if(fork() > 0){
exit(0);
}
close(listen_sock);
char buf[1024];
while(1){
ssize_t s = read(new_sock,buf,sizeof(buf)-1);
if(s > 0){
buf[s] = 0;
printf("client say# %s\n",buf);
write(new_sock,buf,strlen(buf));
}else if(s == 0){
perror("client quit!");
break;
}else{
break;
}
}
exit(0);
}else{//father
close(new_sock);
// if(fork() > 0){
// exit(0);
// }
}
}
}
return 0;
}
2、客户端代码
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<string.h>
#include<netinet/in.h>
int startup(const char *_ip,int _port)
{
int sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0){
perror("socket");
exit(1);
}
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_port = htons(_port);
local.sin_addr.s_addr = inet_addr(_ip);
socklen_t lenth = sizeof(local);
int opt = 1;
setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
if(bind(sock,(struct sockaddr*)&local,lenth) < 0){
perror("bind");
exit(2);
}
if(listen(sock,10) < 0){
perror("listen");
exit(3);
}
return sock;
}
static void usage(const char* proc)
{
printf("[local_ip] [local_port]\n",proc);
}
int main(int argc,char *argv[])
{
if(argc != 3){
usage(argv[0]);
return 1;
}
int listen_sock = startup(argv[1],atoi(argv[2]));
struct sockaddr_in client;
socklen_t len = sizeof(client);
while(1){
int new_sock = accept(listen_sock,(struct sockaddr*)&client,&len);
if(new_sock < 0){
perror("new_sock");
exit(0);
}else{
pid_t id = fork();
if(id == 0){//child
if(fork() > 0){
exit(0);
}
close(listen_sock);
char buf[1024];
while(1){
ssize_t s = read(new_sock,buf,sizeof(buf)-1);
if(s > 0){
buf[s] = 0;
printf("client say# %s\n",buf);
write(new_sock,buf,strlen(buf));
}else if(s == 0){
perror("client quit!");
break;
}else{
break;
}
}
exit(0);
}else{//father
close(new_sock);
// if(fork() > 0){
// exit(0);
// }
}
}
}
return 0;
}
3、运行结果