套接字编程中的访问阻塞
Blocking of access in Socket programming
我已经用c++和c++实现了一个简单的回显服务器
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int PORT_NUM = 10000;
int echo_server()
{
const int BUFSIZE = 10;
struct sockaddr_in addr, cli_addr;
bzero((char *) &addr, sizeof(addr));
bzero((char *) &cli_addr, sizeof(cli_addr));
socklen_t addr_len;
char buf[BUFSIZE];
int n_handle;
int s_handle = socket (AF_INET, SOCK_STREAM, 0);
if (s_handle == -1) return -1;
// Set up the address information where the server listens
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT_NUM);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(s_handle, (struct sockaddr *) &addr, sizeof(addr))== -1)
{
return -1;
}
if (listen(s_handle,SOMAXCONN) == -1)
{
return -1;
}
addr_len = sizeof(cli_addr);
n_handle = accept(s_handle, (struct sockaddr *) &cli_addr, &addr_len);
if (n_handle != -1)
{
int n;
int m = 0;
int c = 0;
while ((n = read(n_handle, buf, sizeof buf )) > 0)
{
while (m < n)
{
c = write(n_handle, buf, n);
cout << buf << "-" << c;
m += c;
}
}
close(n_handle);
}
return 0;
}
int main()
{
cout << "TestServer";
return echo_server();
}
当我启动应用程序时,main中的cout被抑制,因为echo服务器函数中的accept语句。只有在我发送一些文本并且函数终止之后,程序才会在主程序中提示退出。
为什么?它是否与访问函数的阻塞行为有关?
我建议冲洗输出,如
cout << buf << "-" << c << endl;
或
cout << "TestServer" << flush;
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- C++ Windows - 以编程方式检查软件是否访问互联网?
- 可编程访问正确的虚拟班级儿童
- 如何通过 Windows SDK 以编程方式访问"netsh"API
- 有没有办法在函数以编程方式返回的引用上多次调用函数? -元组动态访问
- 'Good'通过条目维护/更新/访问文件的编程形式
- 如何以编程方式循环访问所有 CMake 目标
- 如何以编程方式阻止/允许访问工作站(Windows)
- 使用USB编程访问多个网络摄像头
- 使用C++编程访问C驱动器
- 如何以编程方式访问c/c++a-la-rdtsc中的性能计数器
- 我需要使用 ext4 文件以编程方式获取和设置 Ubuntu 14.04 台式计算机的 ACL(访问控制列表)
- 套接字编程中的访问阻塞
- 如果需要,我将如何以编程方式访问或打开交换 edb 文件
- C++,有没有办法以编程方式在Chrome中打开网页并访问其内容
- 访问冲突读取位置0xfeeefef2多线程编程c++窗口