Linux 套接字程序只是冻结而没有错误
Linux socket program just freezes without error
我最近使用Windows进行套接字编程,但我的作业要求学生使用Linux Socket header(sys/socket.h(而不是Windows。所以我从零开始,但程序冻结,即使它是一个非常简单的程序,它什么都不做,只在建立连接时打印一条消息。
服务器.cpp
#include <sys/socket.h>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <errno.h>
#include <string>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 3490
#define BACKLOG 10
int main(void){
int sockfd, new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
socklen_t sin_size;
if((sockfd = socket(PF_INET, SOCK_STREAM, 0))==-1){
perror("Socket creation failed");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(PORT);
my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(sockfd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr))==-1){
perror("Socket binding failed");
exit(1);
}
if(listen(sockfd, BACKLOG) == -1){
perror("Socket listening failed");
exit(1);
}
sin_size = (socklen_t)sizeof(struct sockaddr_in);
while(true){
printf("Loop Test"); // This is not displayed at all
if((new_fd = accept(sockfd, (struct sockaddr*)&their_addr, &sin_size))==-1){
perror("Connetion accepting failed");
exit(1);
}
printf("Server got connection from %sn", inet_ntoa(their_addr.sin_addr));
}
return 0;
}
客户端.cpp
#include <sys/socket.h>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <errno.h>
#include <string>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 3490
int main(void){
int sockfd;
struct sockaddr_in their_addr;
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
perror("Socket generating failed");
exit(1);
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(PORT);
their_addr.sin_addr.s_addr = INADDR_LOOPBACK;
if(connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr)) == -1){
perror("Connection failed");
exit(1);
}
printf("Loop test"); // This is not displayed no matter if server is on or not
return 0;
}
正如我在代码中提到的,它只是停止,并且不显示错误和 printf(用于调试(。为什么会这样?(我正在使用 Ubuntu(
您的程序有两个问题。第一个相对较小,就是你不要用"n"
结束你的printf
语句。因此,输出是缓冲的,您不会立即看到它。
但是,如果您没有一个简单但烦人的错误,那么仅此将不可见(尽管它确实使调试变得更加困难,因为您不确定发生了什么( - 您无法使用 htonl
将INADDR_LOOPBACK转换为大端序。具有讽刺意味的是,你这样做是为了INADDR_ANY
(虽然好的风格并没有做任何真正的事情,因为 0 总是 0(,但不要在真正重要的地方这样做。
相关文章:
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 我的代码中有错误,未声明的标识符
- C++ LeetCode #377 的 DP 解决方案中,此代码是否有错误?
- 试图建立银行管理系统,但有错误
- 我试图创建临时对象的方式有错误吗
- 我的随机生成器是否不工作,或者我决定人/骨架是否击中对手的方式是否有错误
- 我在OpenCV中有错误的"approxPolyDP(ROI_Vertices, ROI_Poly, 1.0, true)"
- 我在这个 C++ 代码上有错误吗?
- 是视觉C++优化器错误还是我的代码中有错误?
- 为什么一个简单的C++程序会有错误的结果?是 #define 引起的吗?
- 对此有错误
- 如何在可滚动的 QTableWidget 中有一个冻结的水平标题?
- C :数据文件有错误:预期的无限制ID
- 一个带有参数的程序,为什么此程序有错误的答案
- 仅使用boost.datetime在Windows上有错误
- 使用向量循环时,是否有错误
- Microsoft Visual Studio发现我所有的CUDA设备端函数都有错误
- 继承默认构造函数在 gcc 中失败并在 clang 中工作,哪个有错误?
- 为什么有错误未定义_getws_s
- 在快速排序程序中有错误