[英]linux c client - add ability of sending data
I try to write a simple Client connecting to beej server stream everything I wrote till now working fine.我尝试编写一个简单的客户端连接到 beej 服务器流我写的所有内容,直到现在工作正常。 now I want to add to the client the ability to send data witch he gets from the user and I don't know how to do it(without using scanf ofc).现在我想向客户端添加发送他从用户那里获得的数据的能力,但我不知道该怎么做(不使用 scanf ofc)。 how can I do it?我该怎么做? this is my code :这是我的代码:
// 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");
After that use send.之后使用发送。
EDIT: You want to implement this function I wrote above.编辑:你想实现我上面写的这个功能。 After that you will make a while loop:之后你会做一个while循环:
while(1)
{
msg=input("Enter the message");
send(sock, msg, strlen(msg), 0);
}
This will allow you to have infinite loop of entering a message and sending it to server.这将允许您无限循环输入消息并将其发送到服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.