2016-05-12 48 views
1

我尝试写一个简单的客户端连接到beej服务器流 我写到现在为止工作正常。 现在我想添加到客户端发送他从用户获得的数据的能力,我不知道该怎么做(不使用scanf ofc)。 我该怎么办? 这是我的代码:linux c客户端 - 添加发送数据的能力

// chat client 

#include <stdio.h> 
#include <sys/socket.h> 
#include <arpa/inet.h> //inet_addr 
#include <netinet/in.h> 
#include <string.h> 
#include <signal.h> 

#define PORT 9034 // defined port like the server 
void main() 
{ 
    char * msg = "omri is here"; 
    char buf[256]; 
    int len = strlen(msg); 
    int byte_sent; 
    int socket_dect; // creating socket descriptor 
    struct sockaddr_in ServerInfo; 
    // creating a new socket, its a number represent a file descriptor 
    // socket args : 1)ip protocol ipv4,second tcp/udp, third is number of protocol used 
    socket_dect = socket(AF_INET,SOCK_STREAM,0); 

    if(socket_dect == -1){ 
     perror("error creating socket"); 
    } 
    // fill the values of the server 
    ServerInfo.sin_family = AF_INET; // ipv4 
    ServerInfo.sin_port = htons(PORT); // port number 
    //ServerInfo.sin_addr = 127.0.0.1; 
    inet_pton(AF_INET, "127.0.0.1", &ServerInfo.sin_addr);//insert the ip to the sin addr 

    // making the connection to the server 
    //ServerInfo.sin_addr.s_addr = inet_addr("127.0.0.1"); // another way to put ip addr 
    connect(socket_dect,(struct sockaddr *)&ServerInfo,sizeof(ServerInfo)); // connected to the server 

    //signal(SIGALRM,sigAlarm); 
    // seng data 
    if(send(socket_dect,msg,len,0) < 0){ 
     perror("send connection"); 
     printf("send error"); 
    } 
    if(recv(socket_dect,buf,len,0) < 0){ 
     printf("recv error"); 
    } 
    printf("the data reviced from the server is :%s\n",buf); 
} 

回答

1
char *input(char *output) 
{ 
    char *buffer = NULL; 
    size_t size = 0; 
    int count = 0; 

    printf("%s", output); 
    count = getline(&buffer, &size, stdin); 
    buffer[count-1] = '\0'; 
    return buffer; 
} 

char *msg=input("Enter the message"); 

在使用发送电子邮件后。

编辑:你想实现我上面写的这个功能。之后,您将制作一段时间循环:

while(1) 
{ 
    msg=input("Enter the message"); 
    send(sock, msg, strlen(msg), 0); 
} 

这将允许您无限循环地输入消息并将其发送到服务器。

+0

让我知道这是否解决了您的问题。 – Mirakurun

+0

你能解释一下这个应该做什么以及它如何解决我的问题? 只是为了确保我让自己清楚 - 当我运行客户端时,我希望他处于无限循环中,并且当用户在cli中键入somthing时,我想发送它。 –

+0

让我编辑它。 – Mirakurun