在Scanf之前发送/接收套接字编程

时间:2016-12-27 21:21:56

标签: c sockets

我试图通过服务器在2个客户端之间建立连接。在此程序中,客户端向服务器发送消息,服务器将其发布到目标客户端。但是这个操作之间有一点问题。发送器在接收到一些消息之前不能发送另一个消息,或者在发送消息之前无法看到接收到的消息。视频应该更好地解释。

  

您可以在client.c代码

下面找到scanf函数

客户端

//
// Created by berkin on 18.12.2016.
//

#include<stdio.h>
#include<sys/socket.h>
#include<arpa/inet.h> // for inet_addr
#include <string.h>
#include <zconf.h>

int main(int argc, char *argv[]) {
    int  sock;
    struct sockaddr_in server;
    char message[2000], server_reply[2000];

    //Create socket
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1) {
        printf("Could not create socket");
    }

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family      = AF_INET;
    server.sin_port        = htons(8888);

    //Connect to remote server
    if (connect(sock, (struct sockaddr *) &server, sizeof(server)) < 0) {
        perror("Connect failed. Error");
        return 1;
    }

    puts("Connected to server\n");


    //keep communicating with server
    while (1) {
        printf("> ");
        scanf("%[^\n]%*c", message);
        fflush(stdin);

        //Send some data
        if (send(sock, message, strlen(message)+1, 0) < 0) {
            puts("Send failed");
            return 1;
        }


        if (recv(sock, server_reply, 2000, 0) < 0) {
            puts("recv failed");
            break;
        }

        //Receive a reply from the server

        printf ("\033[32;1m %s \033[0m\n",server_reply);
    }

    close(sock);
    return 0;
}

SERVER

#include<stdio.h>
#include<string.h>    // for strlen
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h> // for inet_addr
#include<unistd.h>    // for write
#include<pthread.h>   // for threading, link with lpthread
#include "split.h"

#define MAX_CLIENT_NUMBER 100

void *connection_handler(void *);

struct User {
    char userName[10];
    int  clientSocketNo;
};

unsigned int clientNumber = 0;
unsigned int userArrayIndex = 0;
struct User users[MAX_CLIENT_NUMBER];

//FOR GETUSERS COMMAND
void getUsers(int socketNumber) {
    char *userString = malloc(100);
    if (users[0].userName != NULL) {
        strcpy(userString, users[0].userName);
        strcat(userString, ",");
    } else {
        return;
    }

    for (int i = 1; i < userArrayIndex; ++i) {
        strcat(userString, users[i].userName);
        strcat(userString, ",");
    }
    write(socketNumber, userString, strlen(userString) + 1);
}

//AFTER LOGIN COMMAND, ADD TO THE ARRAY
void addUserToArray(char userName[10], int socketNumber) {
    printf("Client logged in as %s\n", userName);
    strcpy(users[userArrayIndex].userName, userName);
    users[userArrayIndex].clientSocketNo = socketNumber;
    userArrayIndex++;
}

//LOGIN COMMAND
void loginUser(char userName[10], int socketNumber) {
    char *message = "login successful";
    write(socketNumber, message, strlen(message) + 1);
    addUserToArray(userName, socketNumber);
}

//SEND MESSAGE IF USER FOUND
void sendMessage(struct User user, char *message){
    write(user.clientSocketNo,message,strlen(message) + 1);
}

//SEARCH USER FROM ARRAY
struct User searchUser(char searchName[10]){
    for (int i = 0; i < userArrayIndex; ++i) {
        if(strcmp(users[i].userName,searchName) == 0){
            return users[i];
        }
    }
}

void *connection_handler(void *socket_desc) {
    //Get the socket descriptor
    char receivedMessage[2000];  //client's message

    int readControl;
    int parsedItemNumber = 0;
    int sock = *((int *) socket_desc);

    while ((readControl = recv(sock, receivedMessage, 2000, 0)) > 0) {
        char *parsedCommand[50]; //parsedClientMessage

        parsedItemNumber = parsing(parsedCommand, receivedMessage, " ");

        if (strcmp(parsedCommand[0], "login") == 0) {
            loginUser(parsedCommand[1], sock);
        }

        else if (strcmp(parsedCommand[0], "getusers") == 0) {
            getUsers(sock);
        }

        else if (strcmp(parsedCommand[0], "exit") == 0) {
            close(sock);
            return 0;
        }
        else{
            if(parsedCommand[0] != NULL){
                struct User find = searchUser(parsedCommand[0]);
                if(find.userName != NULL){
                    char *message = malloc(2000);
                    if(parsedCommand[1] != NULL){
                        strcpy(message,parsedCommand[1]);
                        strcat(message," ");
                    }
                    for (int i = 2; i < parsedItemNumber; ++i) {
                        strcat(message,parsedCommand[i]);
                        strcat(message," ");
                    }

                    sendMessage(find,message);
                }
                else{
                    perror("Your input was wrong");
                }
            }
        }
    }

    if (readControl == 0) {
        puts("Client disconnected");
        clientNumber--;
        fflush(stdout);
    } else if (readControl == -1) {
        perror("recv failed");
    }

    //Free the socket pointer
    free(socket_desc);
    return 0;
}

int main(int argc, char *argv[]) {

    int                socket_desc, new_socket, c, *new_sock;
    struct sockaddr_in server, client;

    //Create Socket
    socket_desc = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_desc == -1) {
        puts("Could not create socket");
        return 1;
    }

    server.sin_family      = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port        = htons(8888);

    if (bind(socket_desc, (struct sockaddr *) &server, sizeof(server)) < 0) {
        puts("Binding failed");
        return 1;
    }

    listen(socket_desc, 3);

    puts("Server started");
    c                  = sizeof(struct sockaddr_in);
    while ((new_socket = accept(socket_desc, (struct sockaddr *) &client, (socklen_t *) &c)) &&
           clientNumber < MAX_CLIENT_NUMBER) {
        pthread_t sniffer_thread[MAX_CLIENT_NUMBER];
        new_sock = malloc(1);
        *new_sock = new_socket;

        if (pthread_create(&sniffer_thread[clientNumber], NULL, connection_handler,
                           (void *) new_sock) < 0) {
            perror("Could not create thread");
            return 1;
        } else {
            clientNumber++;
        }

        puts("Client connected");
    }


    if (new_socket < 0) {
        perror("accept failed");
        return 1;
    }

    return 0;
}

0 个答案:

没有答案