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);
}
让我知道这是否解决了您的问题。 – Mirakurun
你能解释一下这个应该做什么以及它如何解决我的问题? 只是为了确保我让自己清楚 - 当我运行客户端时,我希望他处于无限循环中,并且当用户在cli中键入somthing时,我想发送它。 –
让我编辑它。 – Mirakurun