gpt4 book ai didi

c - 我在套接字程序中得到了一个奇怪的词 'Received: 艎��'

转载 作者:行者123 更新时间:2023-12-03 11:54:41 24 4
gpt4 key购买 nike

我编写了一个服务器程序和一个客户端程序,这些程序与linux ubuntu上的套接字进行通信。客户端程序输出Received: 艎��这是我的服务器代码:

/*** tcp_server.c ***/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main() {
int sock_fd, new_fd, bytes;
struct sockaddr_in seraddr, cliaddr;
char data[1024];
socklen_t cli_addr_size;
cli_addr_size = sizeof(cliaddr);

sock_fd = socket(AF_INET, SOCK_STREAM, 0);

memset(&seraddr, 0, sizeof(seraddr));
seraddr.sin_family = AF_INET;
seraddr.sin_addr.s_addr = htonl(INADDR_ANY); // INADDR_ANY : It received Network Interface that connected server defined interface, htonl :
seraddr.sin_port = htons(5050);
bind(sock_fd, (struct sockaddr *)&seraddr, sizeof(seraddr));
listen(sock_fd, 10);
while (1) {
new_fd = accept(sock_fd, (struct sockaddr *)&cliaddr, &cli_addr_size);
bytes = recv(new_fd, data, 1024, 0);
send(new_fd, data, bytes, 0);
close(new_fd);
}

close(sock_fd);
}
我的客户代码是:
/*** tcp_client.c ***/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

int main(int argc, char *argv[]) {
int sock_fd, bytes;
struct sockaddr_in ser_addr;
char *snddata, rcvdata[1024];

snddata = argv[2];
sock_fd = socket(AF_INET, SOCK_STREAM, 0);

memset(&ser_addr, 0,sizeof(ser_addr));
ser_addr.sin_family = AF_INET;
ser_addr.sin_addr.s_addr = inet_addr(argv[1]); // INADDR_ANY : It received Network Interface that connected server defined interface, htonl :
ser_addr.sin_port = htons(5050);
connect(sock_fd, (struct sockaddr *)&ser_addr, sizeof(ser_addr));
send(sock_fd, snddata, strlen(snddata), 0);
printf("Received: ");

bytes = recv(sock_fd, rcvdata, 1024, 0);
rcvdata[bytes] = '\0';
printf("%s\n", rcvdata);

close(sock_fd);
}
首先,我收到了 accept的参数3的错误,然后我更改了
        new_fd = accept(sock_fd, (struct sockaddr *)&cliaddr, sizeof(cliaddr);
但是它仍然产生这个奇怪的词。

最佳答案

尝试更改send()和receive()函数,以便完全控制从缓冲区(data[1024])发送多少个字节和,例如此线程:C socket: recv and send all data,另请参阅Beej的网络编程指南( http://beej.us/guide/bgnet/ )
还要确保初始化数据缓冲区:

data[1024] = "";
rcvdata[1024] = "";
或者
 data[1024];
data[0] = '\0';
rcvdata[1024];
rcvdata[0] = '\0';
,背景位于此线程中:Why I am getting this unusually symbols by printing char string

关于c - 我在套接字程序中得到了一个奇怪的词 'Received: 艎��',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66611259/

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