【发布时间】:2016-02-26 21:49:24
【问题描述】:
为我的家庭考试在 c 中创建一个 tcp 客户端 服务器程序。在服务器和客户端之间接收和发送数据时遇到了一些问题。我只能接收一个字节,如果我发送“abcd”我会收到“a”。
(这是双向发生的,因为我对服务器和客户端使用相同的方法)
不知道是发送部分的问题还是接收部分的问题
这是我的代码:
#define BUFFER_SIZE 1024
char* recived_message;
int send_data(int socket, char* data){
int offset = 0, len = strlen(data);
while (offset != len) {
int nb = send(socket, data + offset, len - offset, 0);
if (nb < 0){
perror("send");
return -1;
}
offset += nb;
}
return 0;
}
int recive(int socket){
int offset = 0;
recived_message = malloc(BUFFER_SIZE);
memset(recived_message, 0, BUFFER_SIZE);
while (offset != BUFFER_SIZE) {
int nb = recv(socket, received_message + offset, BUFFER_SIZE - offset, 0);
if(nb == -1){
perror("read");
return -1;
}else if(nb == 0){
return -1;
}
offset += nb;
}
printf("%d\n", offset);
return 0;
}
char* get_data(){
return recived_message;
}
服务器端
int recive_data(int socket){
char* buffer;
if(recive(socket) != 0){
return -1;
}
*buffer = *get_data();
printf("socket %d: %s\nlength: %lu%", fd, buffer, strlen(buffer));
return 0;
}
部分客户
char* test = "abcd";
for(i=0; i<10; i++) {
send_data(sock, test);
sleep(1);
}
【问题讨论】:
-
您在循环中正确接收,这很好,但是每次您在循环中迭代时,您都会覆盖缓冲区中的先前数据。发送时你做对了,接收时为什么不做?
-
至于您遇到的问题,请告诉我们您是如何使用这段代码的?玩具怎么知道你只收到一个字节?你怎么检查这个?并尝试发送每个角色都是独一无二的东西,现在不可能说它是你看到的第一个还是最后一个角色。哦,你确定问题出在接收而不是发送吗?
-
您的发送(至少)是错误的,您传递了一个 5 字节长的缓冲区
"abcd",但尝试发送BUFFER_SIZE(1024) 字节......你怎么确定你只收到一个字节?
标签: c sockets tcp server client