DSIK_C/main.c

149 lines
3.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <pthread.h>
#include <fcntl.h>
#include "EasySockets.h"
#include "Game.h"
#include "LinkedList.h"
#include "Player.h"
bool wait =false;
void* WaitForInput(){
if (wait) {char c = getchar();}
wait=false;
}
int socket_id;
struct sockaddr_in incoming;
void InterpretReceivedSignal(Player* p, const char* buffer, int len, bool* fileSwitch){
printf("Interpreting: %s", buffer);
if (state==0){
wait=false;
}
else {
if (buffer[0] == 'u') {
p->y = p->y - 1;
} else if (buffer[0] == 'd') {
p->y = p->y + 1;
} else if (buffer[0] == 'l') {
p->x = p->x - 1;
} else if (buffer[0] == 'r') {
p->x = p->x + 1;
}else if (buffer[0] == 'f'){
*fileSwitch=true;
}
}
}
int series =0;
void UpdateStateToClients(){
for (int i =0; i<200; i++){
if (playerConnected[i]){
Player* p_receiver = players[i];
for (int j =0; j<200; j++){
if (playerConnected[j]) {
char* buffer[45];
Player* p = players[j];
sprintf(buffer, "%d,%d,%d,%d,%d\r\n",series, j, p->x, p->y, p->points);
printf(">> %s",buffer);
send(p_receiver->connectionId, buffer, strlen(buffer), 0);
}}
char end[8] = "end\r\n";
send(p_receiver->connectionId, end, strlen(end),0);
}
}
series++;
}
void* PlayerDataReaderThread(void* arg){
char buffer[550];
Player* p = (Player*)arg;
printf("%d", p->points);
socklen_t size = sizeof(p->incoming);
bool isFile=false;
FILE* fileHandle = NULL;
while (true) {
int s = recv(p->connectionId, buffer, 550, 0);
if (s>0) {
if (!isFile)
{InterpretReceivedSignal(p, buffer, 550,&isFile);
continue;}
if (isFile){
printf("is file \n");
if (fileHandle==NULL) fileHandle=fopen("recv", "w+");
//receiving the file in parts
printf("buffer content: %s\n", buffer);
fwrite(buffer,s,1,fileHandle);
if (s<550){
printf("ended receiving file...\n");
//if not data was received
fflush(fileHandle);
fclose(fileHandle);
isFile=false;
}
continue;
}
if (state >0)
UpdateStateToClients();
}else{
}
}
}
void* JoiningThread(){
while (true) {
int a = AcceptClient(socket_id, &incoming);
Player* p = CreatePlayer("tttt", a, incoming);
AddPlayerToList(p);
printf("Players: %d/200", GetPlayersCount());
pthread_create(&p->threadId, NULL, PlayerDataReaderThread, p);
}
return 0;
}
int BeginGame(){
state=1;
}
int main() {
InitPlayers();
setvbuf(stdout, NULL, _IONBF,0);
socket_id = CreateSocket();
//Connect(socket_id, "0.0.0.0", 12345);
int c = CreateServer(socket_id, 1234);
printf("Waiting for players to connect. \n Press any key to start...");
wait=true;
pthread_t thread_id;
pthread_create(&thread_id, NULL, JoiningThread, NULL);
wait=true;
while(wait){}
printf("...");
//pthread_exit(thread_id);
BeginGame();
printf("Press any key to close the server\n");
getchar();
return 0;
}