120 lines
2.5 KiB
C
120 lines
2.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <limits.h>
|
|
|
|
#include <ssocket.h>
|
|
#include <tthread.h>
|
|
#include <iini.h>
|
|
#include <llog.h>
|
|
|
|
#define BUFFER_SIZE 128
|
|
#define CLIENT_SIZE 32
|
|
SOCKET sfd;
|
|
SOCKET cfds[CLIENT_SIZE];
|
|
|
|
void send_the_message(int sock, const char *Buff, int szBuf)
|
|
{
|
|
char Buf[2048] = {0};
|
|
int tempsock;
|
|
sprintf(Buf, "<from %d>:", sock);
|
|
strcat(Buf, Buff);
|
|
|
|
for(int i = 0; i < CLIENT_SIZE; i++) {
|
|
if(cfds[i] != 0 && cfds[i] != sock) {
|
|
tempsock = cfds[i];
|
|
send(tempsock, Buf, strlen(Buf)+1, 0);
|
|
}
|
|
}
|
|
}
|
|
|
|
void receive_message(void* param)
|
|
{
|
|
int res;
|
|
char Buf[1024] = {0};
|
|
int sock = *((SOCKET*)param);
|
|
free(param);
|
|
printf("recv start %d\n", sock);
|
|
while(1) {
|
|
res = recv(sock, Buf, sizeof(Buf), 0);
|
|
if(res == -1 || res > sizeof(Buf) || res == 0) {
|
|
#if WIN_PART
|
|
printf("<error: %d>\n", GetLastError());
|
|
#elif LINUX_PART
|
|
perror("recv error");
|
|
#endif
|
|
break;
|
|
}
|
|
printf("recv buf:%d,%s",res, Buf);
|
|
send_the_message(sock, Buf, strlen(Buf)+1);
|
|
}
|
|
printf("<socket = %d> exit\n", sock);
|
|
for(int i = 0; i < CLIENT_SIZE; i++) {
|
|
if(cfds[i] == sock) {
|
|
cfds[i] = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
void acceptfunc(void* param) {
|
|
char *ip;
|
|
unsigned short port;
|
|
SOCKET* psock;
|
|
SOCKET sock;
|
|
while(1) {
|
|
psock = (SOCKET*)malloc(sizeof(SOCKET));
|
|
if(psock == NULL) {
|
|
exit(-1);
|
|
}
|
|
if (sock_accpet(sfd, &sock, &ip, &port) != 0) {
|
|
continue;
|
|
}
|
|
*psock = sock;
|
|
for(int i = 0; i < CLIENT_SIZE; i++) {
|
|
if(cfds[i] == 0) {
|
|
cfds[i] = sock;
|
|
printf("<ip = %s, port = %u, socket = %lld>\n", ip, port, sock);
|
|
free(ip);
|
|
thread_create(NULL, receive_message, (void*)psock);
|
|
goto CONTINUE;
|
|
}
|
|
}
|
|
printf("client full");
|
|
exit(-2);
|
|
CONTINUE:
|
|
psock = NULL;
|
|
}
|
|
}
|
|
|
|
#define _STR(str) #str
|
|
#define STR(str) _STR(str)
|
|
|
|
int main()
|
|
{
|
|
char param[2][BUFFER_SIZE] = { 0 };
|
|
char Buf[BUFFER_SIZE];
|
|
int szbuf = BUFFER_SIZE;
|
|
szbuf -= ini_get_str("server.ini", "base", "server_ip", _SOCKET_TEST_IP4, param[0], BUFFER_SIZE);
|
|
ini_get_str("server.ini", "base", "server_port", STR(_SOCKET_TEST_PORT), param[1], BUFFER_SIZE);
|
|
|
|
void* ptr = NULL;
|
|
int res = make_server_sock_ex(&sfd, param[0], param[1], &ptr);
|
|
freeaddrinfo(ptr);
|
|
|
|
if(res != 0) {
|
|
printf("server start error\npress enter to continue");
|
|
getchar();
|
|
return 0;
|
|
}
|
|
printf("server start...\n");
|
|
thread_create(NULL, acceptfunc, NULL);
|
|
while(1) {
|
|
fgets(Buf, sizeof(Buf), stdin);
|
|
printf("%s", Buf);
|
|
if(strncasecmp(Buf, "exit", strlen("exit")) == 0) {
|
|
printf("exit success\npress enter to continue");
|
|
getchar();
|
|
exit(-1);
|
|
}
|
|
}
|
|
return 0;
|
|
} |