1. 介绍
服务器和 客户端1 和 客户端2通信。
2.server.c
/*
* socket
* bind
* send/recv
*/
#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>
#include <signal.h>
#define SERVER_PORT 8888
int main(int argc, char **argv)
{
int server;
int client;
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
int ret;
int server_recv;
int addr_len;
unsigned char recvbuf[1000];
int client_num = -1;
server = socket(AF_INET, SOCK_DGRAM, 0);
if (server == -1){
printf("soket error!\n");
return -1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
memset(server_addr.sin_zero, 0, 8);
/* 将文件句柄绑定ip和端口*/
ret = bind(server, (const struct sockaddr *)&server_addr,
sizeof(struct sockaddr));
if (ret == -1){
printf("bind error!\n");
return -1;
}
while (1) {
addr_len = sizeof(struct sockaddr);
server_recv = recvfrom(server, recvbuf, 999, 0,
(struct sockaddr *)&client_addr, &addr_len);
if (server_recv > 0){
client_num++; /* 统计客户端*/
printf("get connect form client %d : %s \n", client_num,
inet_ntoa(client_addr.sin_addr));
recvbuf[server_recv]= '\0';
printf("get msg form %s : %s\n", inet_ntoa(client_addr.sin_addr), recvbuf);
}
}
close(server);
return 0;
}
2. client.c
/*
* socket
* connect
* send/recv
*/
#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 8888
int main(int argc, char **argv)
{
int client;
struct sockaddr_in server_addr;
int ret;
unsigned char sendbuf[1000];
int client_send;
if (argc != 2){
printf("Usage: %s <server_ip>\n", argv[0]);
return -1;
}
client = socket(AF_INET, SOCK_DGRAM, 0);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
memset(server_addr.sin_zero, 0, 8);
if (inet_aton(argv[1], &server_addr.sin_addr) == 0){
printf("invalid server_ip\n");
return -1;
}
/* 连接服务器 */
ret = connect(client, (const struct sockaddr *)&server_addr,
sizeof(struct sockaddr));
if (ret == -1){
printf("connect error!\n");
return -1;
}
while (1){
if (fgets(sendbuf, 999, stdin)){
/* 发送数据给服务器 */
client_send = send(client, sendbuf, strlen(sendbuf), 0);
if (client_send <= 0){
close(client);
return -1;
}
}
}
return 0;
}