c - linux c client - 添加发送数据的能力

标签 c linux sockets

我尝试编写一个连接到 beej 服务器流的简单客户端 到目前为止,我写的所有内容都运行良好。 现在我想向客户端添加发送他从用户那里获得的数据的能力,但我不知道该怎么做(不使用 scanf ofc)。 我该怎么做? 这是我的代码:

// 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);
}

最佳答案

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 循环:

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

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

关于c - linux c client - 添加发送数据的能力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192761/

相关文章:

C 数组的值随机变化

使用系统调用在 C 中复制文件并将其转换为二进制文件

linux - 这个命令有什么作用? "exec bash -l"

c - 多进程如何绑定(bind)到一个udp端口

c++ - C++代码中的字节序影响

c++ - #ifdef标志来说明gcc和g++编译器之间的区别?

c - 我想做一个打印反向的代码

c - sscanf 和正确的格式文件

c++ - 在 C++ 中,为什么无法初始化指向函数的指针?

java - 如何在java聊天中更新JList