2016-04-04 10 views
2

はASIO UDPソケット(以下バージョンを後押し)ASIO UDPソケットが受け取る

asio::io_service service; 
asio::ip::udp::socket sock(service); 
asio::ip::udp::endpoint endpoint(asio::ip::address::from_string("127.0.0.1"), 20100); 

sock.connect(endpoint); 
sock.send(buffer("testing\n")); 

std::string buffer; 
size_t length = sock.receive(asio::buffer(buffer)); <--- spawn exception 

で受信/送信するためにこのコードを試みたが失敗しましたが、次のエラーました:ここが間違っ

An existing connection was forcibly closed by the remote host 

何か?助けてくれてありがとう!

+0

@EJP可能です - > http://stackoverflow.com/questions/34224443/an-existing-connection-was-forcibly-closed-by-the-remote-host-when-listening-f – leon22

+0

できますかUDPソケットがポート「20100」にバインドされていることを確認してください。接続されたUDPソケットの場合、宛先アドレスに受信者がない場合、 'send()'を呼び出した後、 'send()'と 'receive()'のそれ以降の呼び出しは 'ECONNREFUSED'で失敗する可能性があります。 –

+0

@TannerSansburyこれをどのように確認できますか? (TCPソケットを使用しても問題はありませんが、速度の理由からUDPに切り替える必要があります) – leon22

答えて

1

あなたのudpサーバーをどのように構築するのか分かりませんが、間違っていると思います。私はsend()が成功したポート9090に何のUDPソケットがバインドされていないローカルホストまたは任意のホストでUDPポート9090にデータを送信しようとしたがrecv()

#include <stdio.h> 
#include <errno.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <arpa/inet.h> 

int main() 
{  
    struct sockaddr_in addr; 
    int fd, cnt, ret; 

    if ((fd=socket(AF_INET, SOCK_DGRAM, 0)) < 0) { 
     printf("error"); 
     exit(1); 
    } 

    memset(&addr, 0, sizeof(addr)); 
    addr.sin_family=AF_INET; 
    addr.sin_addr.s_addr=inet_addr("127.0.0.1"); 
    addr.sin_port=htons(9090); // address which is not bound 

    ret = connect(fd,(struct sockaddr *)&addr,sizeof(addr)); 
    char buf[512]; 

    cnt = send(fd, "hello", sizeof("hello"), 0); 
    if(cnt < 0) 
     perror("send:"); 
    cnt = recv(fd, buf, 512, 0); // error: Connection refused 
    if(cnt < 0) 
     perror("recv:"); 

    return 0; 
} 

:私はあなたが得るエラーメッセージを説明するためのプログラム例を書きます失敗する。 man page for udpによると:

All fatal errors will be passed to the user as an error return even when the socket is not connected. This includes asynchronous errors received from the network. You may get an error for an earlier packet that was sent on the same socket. This behaviour differs from many other BSD socket implementations which don't pass any errors unless the socket is connected. Linux's behaviour is mandated by According to the rfc 1122

言うた:

UDP MUST pass to the application layer all ICMP error messages that it receives from the IP layer. Conceptually at least, this may be accomplished with an upcall to the ERROR_REPORT routine

send()が成功したが、それは、ICMPエラーメッセージが表示され、その後recv()はあなたがかもしれないこのエラー(を見て、(あなたはtcpdumpのでそれを見ることができます)同じソケットで送信された先のパケットのエラーを受け取ります。)、失敗します。

関連する問題