C ++奇怪的套接字数据 [英] C++ strange socket data

查看:228
本文介绍了C ++奇怪的套接字数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,这里是我的代码。

  int main(){

char buffer [BUFSIZE];

//定义我们的地址结构,存储我们的端口
//和我们的ip地址,以及套接字类型等等。
struct sockaddr_in addrinfo;
addrinfo.sin_family = AF_INET;
addrinfo.sin_port = htons(PORT);
addrinfo.sin_addr.s_addr = INADDR_ANY;


//创建我们的套接字。
int sock;
if((sock = socket(addrinfo.sin_family,SOCK_STREAM,0))< 0){
cout< 创建套接字时出错。
}

//将我们的套接字绑定到我们想要的实际地址
if(bind(sock,(struct sockaddr *)& addrinfo,sizeof(addrinfo))! 0){
cout<< 绑定中出错。
}

//打开用于侦听的套接字
if(listen(sock,5)!= 0){
cout< 打开侦听器时出错。
}
cout<< 等待连接....< endl;

char * msg =成功!You are connected.\r\\\
;

//连续接受新连接..但没有多线程..
while(1){

struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(client_addr);

if(int client = accept(sock,(struct sockaddr *)& client_addr,& sin_size)){
cout< Recired new connection from<< inet_ntoa(client_addr.sin_addr)<< endl;
send(client,msg,strlen(msg),0);
while(1){
send(client,buffer,recv(client,buffer,BUFSIZE,0),0);

cout<<缓冲液< endl;
strcpy(buffer,);
}

} else {
cout<< 接受新连接时出错。 << endl;
}

}

close(sock);
return 0;
}

现在,我是新的socket,Im只是试图得到他们的感觉,但我有一些经验与套接字在PHP。我使用telnet通过putty在我的linux机器测试这,我不知道是否导致任何问题,但服务器输出一些奇怪的字符,我不知道为什么。我认为它与缓冲区有关,但我不是很确定。我可以通过telnet发送像hi到服务器,并输出它们很好,并将它们发送给我,但当我发送的东西,如hoobla,它开始有趣的字符的东西。任何建议都会有所帮助!



提前感谢!

解决方案

因为 recv 不会终止您的缓冲区。



下面代码中的重要部分是: p>

  int num = recv(client,buffer,BUFSIZE,0); 
if(num <1)break;

send(client,>>,3,0); //<< - 很高兴。
send(client,buffer,num,0);

buffer [num] ='\0'; //<< - 真的重要的位!

if(buffer [num-1] =='\\\
')//<< - 很高兴。
buffer [num-1] ='\0'; //<< - 很高兴。

cout<<缓冲液< endl;

这将正确地终止您的缓冲区,然后尝试打印它,以及删除尾部换行(和允许客户端区分输入和回显线)。



这一个(一个完整的程序)工作更好:

  using namespace std; 
#include< iostream>
#include< sys / socket.h>
#include< arpa / inet.h>

#define BUFSIZE 1000
#define PORT 1234

int main(){
char buffer [BUFSIZE];

//定义我们的地址结构,存储我们的端口
//和我们的ip地址,以及套接字类型等等。
struct sockaddr_in addrinfo;
addrinfo.sin_family = AF_INET;
addrinfo.sin_port = htons(PORT);
addrinfo.sin_addr.s_addr = INADDR_ANY;

//创建我们的套接字。
int sock;
if((sock = socket(addrinfo.sin_family,SOCK_STREAM,0))< 0){
cout< 创建套接字时出错。
return -1;
}

//将我们的套接字绑定到我们想要的实际地址
if(bind(sock,(struct sockaddr *)& addrinfo,sizeof(addrinfo))! 0){
cout<< 绑定中出错。
return -1;
}

//打开用于侦听的套接字
if(listen(sock,5)!= 0){
cout< 打开侦听器时出错。
return -1;
}

char * msg =Success!You are connected.\r\\\
;

//连续接受新连接..但没有多线程..
while(1){
cout< 等待连接....< endl;

struct sockaddr_in client_addr;
socklen_t sin_size = sizeof(client_addr);

if(int client =
accept(sock,(struct sockaddr *)& client_addr,& sin_size))
{
cout< 收到来自
<< inet_ntoa(client_addr.sin_addr)<< endl;
send(client,msg,strlen(msg),0);
while(1){
int num = recv(client,buffer,BUFSIZE,0);
if(num <1)break;
send(client,>>,3,0);
send(client,buffer,num,0);

buffer [num] ='\0';
if(buffer [num-1] =='\\\
')
buffer [num-1] ='\0';
cout<缓冲液< endl;
strcpy(buffer,);
}
} else {
cout< 接受新连接时出错。 << endl;
}
}
close(sock);
return 0;
}

在客户端:

  $ telnet 127.0.0.1 1234 
尝试127.0.0.1 ...
连接到127.0.0.1。
转义字符是'^]'。
取得成功!您已连接。
hello
>> hello
我的名字是pax
>>我的名字是pax
和你?
>>你呢?
< CTRL-D>
外部主机关闭的连接。

,在服务器端:

  $ ./testprog 
等待连接....
从127.0.0.1获取新连接
hello
我的名字是pax
和你?
等待连接....


Hey guys, here is my code.

int main() { 

    char buffer[BUFSIZE]; 

    // define our address structure, stores our port
    // and our ip address, and the socket type, etc.. 
    struct sockaddr_in addrinfo; 
    addrinfo.sin_family = AF_INET; 
    addrinfo.sin_port = htons(PORT); 
    addrinfo.sin_addr.s_addr = INADDR_ANY; 


    // create our socket. 
    int sock; 
    if ( (sock = socket(addrinfo.sin_family, SOCK_STREAM, 0))  < 0) { 
        cout << "Error in creating the socket."; 
    } 

    // bind our socket to the actual adress we want 
    if (bind(sock, (struct sockaddr*)&addrinfo, sizeof(addrinfo)) != 0) { 
        cout << "Error in binding."; 
    } 

    // open the socket up for listening
    if (listen(sock, 5) != 0) { 
        cout << "Error in opening listener."; 
    } 
    cout << "Waiting for connections...." << endl; 

    char *msg = "Success! You are connected.\r\n"; 

    // continuously accept new connections.. but no multithreading.. yet
    while(1) { 

        struct sockaddr_in client_addr;
        socklen_t sin_size = sizeof(client_addr); 

        if(int client = accept(sock, (struct sockaddr*)&client_addr, &sin_size)) { 
            cout << "Recived new connection from " << inet_ntoa(client_addr.sin_addr) << endl; 
            send(client, msg, strlen(msg), 0); 
            while(1) { 
                send(client, buffer, recv(client, buffer, BUFSIZE, 0), 0);

                cout << buffer << endl; 
                strcpy(buffer, ""); 
            } 

        } else { 
            cout << "Error in accepting new connection." << endl; 
        } 

    } 

    close(sock); 
    return 0; 
} 

Now, I'm very new to sockets, Im just sort of trying to get a feel for them but I do have some experience with sockets in PHP. I'm using telnet via putty on my linux machine to test this, I don't know if thats causing any issues but the server is outputting some strange characters and I don't know why. I think it has something to do with the buffer, but I'm not really sure. I can send things like "hi" to the server via telnet and it outputs them just fine and sends them back to me but when I send things like "hoobla" it starts the funky character stuff. Any suggestions would be helpful!

Thanks in advance!

解决方案

You're getting rubbish printed out because recv does not null-terminate your buffer.

The important section in the below code is:

int num = recv(client,buffer,BUFSIZE,0);
if (num < 1) break;

send(client, ">> ", 3, 0);     // <<-- Nice to have.
send(client, buffer, num, 0);

buffer[num] = '\0';            // <<-- Really important bit!

if (buffer[num-1] == '\n')     // <<-- Nice to have.
    buffer[num-1] = '\0';      // <<-- Nice to have.

cout << buffer << endl;

which will properly terminate your buffer before trying to print it, as well as remove the trailing newline if present (and allow the client to distinguish between input and echoed lines).

This one (a complete program) works a little better:

using namespace std;
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>

#define BUFSIZE 1000
#define PORT 1234

int main() {
    char buffer[BUFSIZE];

    // define our address structure, stores our port
    // and our ip address, and the socket type, etc..
    struct sockaddr_in addrinfo;
    addrinfo.sin_family = AF_INET;
    addrinfo.sin_port = htons(PORT);
    addrinfo.sin_addr.s_addr = INADDR_ANY;

    // create our socket.
    int sock;
    if ( (sock = socket(addrinfo.sin_family, SOCK_STREAM, 0))  < 0) {
        cout << "Error in creating the socket.";
        return -1;
    }

    // bind our socket to the actual adress we want
    if (bind(sock, (struct sockaddr*)&addrinfo, sizeof(addrinfo)) != 0) {
        cout << "Error in binding.";
        return -1;
    }

    // open the socket up for listening
    if (listen(sock, 5) != 0) {
        cout << "Error in opening listener.";
        return -1;
    }

    char *msg = "Success! You are connected.\r\n";

    // continuously accept new connections.. but no multithreading.. yet
    while(1) {
        cout << "Waiting for connections...." << endl;

        struct sockaddr_in client_addr;
        socklen_t sin_size = sizeof(client_addr);

        if(int client =
            accept(sock, (struct sockaddr*)&client_addr, &sin_size))
        {
            cout << "Recieved new connection from "
                << inet_ntoa(client_addr.sin_addr) << endl;
            send(client, msg, strlen(msg), 0);
            while(1) {
                int num = recv(client,buffer,BUFSIZE,0);
                if (num < 1) break;
                send(client, ">> ", 3, 0);
                send(client, buffer, num, 0);

                buffer[num] = '\0';
                if (buffer[num-1] == '\n')
                    buffer[num-1] = '\0';
                cout << buffer << endl;
                strcpy(buffer, "");
            }
        } else {
            cout << "Error in accepting new connection." << endl;
        }
    }
    close(sock);
    return 0;
}

On the client side:

$ telnet 127.0.0.1 1234
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Success! You are connected.
hello
>> hello
my name is pax
>> my name is pax
and you?
>> and you?
<CTRL-D>
Connection closed by foreign host.

and, on the server side:

$ ./testprog
Waiting for connections....
Recived new connection from 127.0.0.1
hello
my name is pax
and you?
Waiting for connections....

这篇关于C ++奇怪的套接字数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆