0
我已經實現用C簡單的echo服務器++和g ++阻斷插槽訪問編程
#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();
}
當我開始在主要的COUT被抑制的應用,因爲在回聲服務器功能的接受聲明的。只有當我發送一些文本並且函數終止後,程序纔會在主體中提示cout。
這是爲什麼?它是否與訪問函數的阻塞行爲有關?
我不明白你所說的 「COUT被抑制」 的意思。 –
這與套接字無關。 'cout'只是緩衝。你可能需要刷新它。就這樣。 –
非常感謝您提供的信息 –