gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:54 25 4
gpt4 key购买 nike

我尝试编写一个连接到 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com