服务器端:
server.c:
#include
#include
#include
#include
#include
#include
#include
#include
#define _BACKLOG_ 10
int CreateSock(char *ip, int port)
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
printf("socket error\n");
exit(1);
}
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
inet_pton(AF_INET, ip, &server_addr.sin_addr);
if(bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
{
printf("bind error\n");
close(sock);
exit(2);
}
if(listen(sock, _BACKLOG_) < 0)
{
printf("listen error\n");
close(sock);
exit(3);
}
return sock;
}
void Service(int client_sock)
{
for(;;)
{
char buf[1024];
buf[0] = 0;
int s = read(client_sock, buf, sizeof(buf));
if(s > 0)
{
buf[s-1] = 0;
if(strncasecmp(buf, "quit", 4) == 0)
{
printf("client quit!\n");
exit(0);
}
printf("client:%s\n", buf);
write(client_sock, buf, strlen(buf));
}
}
}
int main(int argc, char *argv[])
{
if(argc < 3)
{
printf("%s [addr]:[port]\n", argv[0]);
exit(1);
}
int sock = CreateSock(argv[1], atoi(argv[2]));
struct sockaddr_in client_addr;
bzero(&client_addr, sizeof(client_addr));
while(1)
{
printf("wait connect!\n");
socklen_t len = 0;
int client_sock = accept(sock, (struct sockaddr*)&client_addr, &len);
if(client_sock < 0)
{
printf("accept arror\n");
continue;
}
char buf_ip[INET_ADDRSTRLEN];
buf_ip[0] = 0;
inet_ntop(AF_INET, &client_addr, buf_ip, sizeof(buf_ip));
printf("get connect, ip is:%s, port is: %d\n", buf_ip, ntohs(client_addr.sin_port));
pid_t pid = fork();
if(pid < 0)
{
printf("fork error");
continue;
}
else if(pid == 0)
{
pid_t pid = fork();
if(pid < 0)
{
printf("fork error");
continue;
}
else if(pid > 0)
exit(4);
}
else
{
wait(NULL);
continue;
}
Service(client_sock);
}
close(sock);
return 0;
}
客户端:
client.c
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
if(argc < 3)
{
printf("%s [addr]:[port]\n", argv[0]);
return 1;
}
int sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0)
{
printf("socket error\n");
return 2;
}
struct sockaddr_in server_addr;
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[2]));
inet_pton(AF_INET, argv[1], &server_addr.sin_addr);
if(connect(sock, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
{
printf("connect error\n");
close(sock);
return 3;
}
printf("connect success!\n");
while(1)
{
char buf[1024];
memset(buf, 0x00, sizeof(buf));
printf("please input:>");
fflush(stdout);
read(0, buf, sizeof(buf));
write(sock, buf, strlen(buf));
if(strncasecmp(buf, "quit", 4) == 0)
{
printf("client quit!\n");
break;
}
int s = read(sock, buf, sizeof(buf));
if(s > 0)
{
buf[s] = 0;
printf("server:%s\n", buf);
}
}
close(sock);
return 0;
}
在同一局域网中,可实现多个客户同时访问同一个服务器