1.服务器端
#include<stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVER_PORT 8080
#define MAX_SERVERS 10
int main(int argc ,char **argv)
{
int fd_socket = 0;
int is_bind = 0;
int is_listen = 0;
int fd_client = 0;
int client_num = 0;
int add_len = 0;
unsigned int recv_len = 0;
struct sockaddr_in sock_server_addr;
socklen_t sock_len;
unsigned char recv_buffer[100] = {'\0'};
fd_socket = socket(AF_INET, SOCK_STREAM, 0);
if(fd_socket == -1)
{
return fd_socket;
}
sock_server_addr.sin_family = AF_INET;
sock_server_addr.sin_port = htons(SERVER_PORT);
sock_server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(sock_server_addr.sin_zero, 0, 8);
is_bind = bind(fd_socket, ( const struct sockaddr *)&sock_server_addr, \
sizeof(struct sockaddr));
if(is_bind == -1)
{
return is_bind;
}
is_listen = listen(fd_socket, MAX_SERVERS);
if (is_listen == -1)
{
return -1;
}
while (1)
{
add_len = sizeof(struct sockaddr);
fd_client = accept(fd_socket, (struct sockaddr *)&sock_server_addr, &add_len);
if(fd_client != -1)
{
client_num++;
printf("Get connection from client %d: %s\n", client_num, inet_ntoa(sock_server_addr.sin_addr));
if (!fork())
{
while (1)
{
recv_len = recv(fd_client, recv_buffer, sizeof(recv_buffer) - 1, 0);
if (recv_len <= 0)
{
close(fd_socket);
return -1;
}
else
{
recv_buffer[recv_len] = '\0';
printf("Got message from client %d: %s\n", client_num, recv_buffer);
}
}
}
}
}
close(fd_socket);
return 0;
}
2.客户端
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVER_PORT 8080
int main(int argc, char **argv)
{
int fd_socket = 0;
int ret;
struct sockaddr_in sock_server_addr;
unsigned char send_buffer[100] = {'\0'};
int send_len;
fd_socket = socket(AF_INET, SOCK_STREAM, 0);
if(fd_socket == -1)
{
printf("built socket err.\n");
return fd_socket;
}
sock_server_addr.sin_family = AF_INET;
sock_server_addr.sin_port = htons(SERVER_PORT);
if (inet_aton("192.168.0.112", &sock_server_addr.sin_addr) == 0)
{
printf("invalid server_ip\n");
return -1;
}
memset(sock_server_addr.sin_zero, 0, 8);
ret = connect(fd_socket, (struct sockaddr *)&sock_server_addr, sizeof(struct sockaddr));
if (ret == -1)
{
printf("connect error!\n");
return -1;
}
while (1)
{
if (fgets(send_buffer, sizeof(send_buffer) - 1, stdin))
{
send_len = send(fd_socket, send_buffer, strlen(send_buffer), 0);
if (send_len <= 0)
{
close(fd_socket);
return -1;
}
else
{
printf("Sent %d bytes.\n", send_len);
}
}
}
return 0;
}
|