首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

小弟我这客户端咋连不上服务器呢

2012-04-21 
我这客户端咋连不上服务器呢C/C++ code#include iostreamusing namespace std#include winsock2.hvoi

我这客户端咋连不上服务器呢

C/C++ code
#include <iostream>using namespace std;#include <winsock2.h>void main(){    cout<<" 服务器 "<<endl;    WSADATA wd;    WSAStartup(MAKEWORD(2,2), &wd);    SOCKET s1 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    if( s1 == INVALID_SOCKET )    {        cout<<"Error 1"<<endl;        return;    }    SOCKADDR_IN tcpaddr;    tcpaddr.sin_family = AF_INET;    tcpaddr.sin_port = htons(5150);    tcpaddr.sin_addr.S_un.S_addr = htonl( INADDR_ANY );    if( SOCKET_ERROR == bind(s1, (SOCKADDR*)&tcpaddr, sizeof(tcpaddr)) )    {        cout<<"bind Error"<<endl;        return;    }    if( WSAEINVAL == listen(s1, 5) )    {        cout<<"Listen Error"<<endl;        return;    }    SOCKADDR_IN ClientAddr;    int len;    SOCKET s2;    while(1)    {        s2 = accept(s1, (SOCKADDR*)&ClientAddr, &len);        if( s2 != INVALID_SOCKET )        {            cout<<"有客户端连入"<<endl;            break;        }    }        //while(1)    //{    //    char buf[1000];    //    ::ZeroMemory(buf,1000);    //    recv(s2, buf,1000, 0);    //    if( strcmp(buf, "") != 0 )    //        cout<<buf<<endl;    //    else    //        break;    //}    WSACleanup();}


C/C++ code
#include <iostream>using namespace std;#include <winsock2.h>void main(){    cout<<" 客户端 "<<endl;    WSADATA wd;    WSAStartup(MAKEWORD(2,2), &wd);    SOCKET s1 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    SOCKADDR_IN add;    add.sin_family = AF_INET;    add.sin_port = htons(5150);    add.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");    int err = connect(s1, (SOCKADDR*)&add, sizeof(add));    if(err == WSAECONNREFUSED)        cout<<"connect error"<<endl;    if(err == WSAETIMEDOUT)        cout<<"CONNECT ERROR"<<endl;    while(1)    {        char buf[1000];        ::ZeroMemory(buf,1000);        cin.getline(buf,1000);        if(  strcmp(buf, "0") == 0 )            break;        else            send(s1, buf, 1000, 0);    }}


[解决办法]
先开的服务器吗

有什么错误或返回值提示
[解决办法]
WSAGetLastError.看看出现的是什么错误

热点排行