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

sock编程出错,帮忙看看呀。解决方法

2012-03-18 
sock编程出错,帮忙看看呀。SOCKET socketSOCKET(AF_INET,SOCK_STREAM,0)if(!socket) std::cout出错

sock编程出错,帮忙看看呀。
SOCKET socket=SOCKET(AF_INET,SOCK_STREAM,0);

 if(!socket) std::cout<<"出错";


不能用socket 换成SOCKET就可以了,但是创建失败

[解决办法]
WSAStartup了吗?
[解决办法]
使用socket要初始化

WSADATA data;
WSAStartup(MAKEWORD(2,0), &data);


使用之后要

WSACleanup();
[解决办法]
给你copy一段代码,自己研究吧

1:客户端
#include <iostream>
#include <WINSOCK2.H>
#pragma comment (lib,"ws2_32.lib")

int main()
{
WSADATA wsaData; //用于填充套接字库版本的有关信息
SOCKET ServerSocket = NULL; //服务器套接字(用于同服务器IPv4地址绑定)
SOCKADDR_IN ServerSocketAddr; //服务器的IPv4地址
int port = 9999; //要连接服务器的端口
char buf[1024]; //存储消息用
int MessageLen = 0; //返回的消息长度

//加载Winsock 2.2版本
if(WSAStartup(MAKEWORD(2,2),&wsaData) !=0)
{
std::cout<<"WSAStartup failed"<<std::endl;
return 1;
}

//创建套接字
if((ServerSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == INVALID_SOCKET)
std::cout<<"Create ServerSocket failed with error"<<" "<<WSAGetLastError()<<std::endl;

//填写服务器IPv4信息
ServerSocketAddr.sin_family = AF_INET;
ServerSocketAddr.sin_port = htons(port);
ServerSocketAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
//连接服务器
if(connect(ServerSocket,(SOCKADDR*)&ServerSocketAddr,sizeof(ServerSocketAddr)) ==SOCKET_ERROR)
std::cout<<"Connecting failed with error"<<" "<<WSAGetLastError()<<std::endl;
else
std::cout<<"Connect successing!"<<std::endl;

//发送数据,直到数据内容为"exit"则退出程序
while(strcmp(buf,"exit") != 0)
{
std::cout<<"Please input:"<<std::endl;
std::cin>>buf;
if((MessageLen = send(ServerSocket,buf,strlen(buf),0)) == INVALID_SOCKET)
std::cout<<"Send data failed with error"<<" "<<WSAGetLastError()<<std::endl;
else
std::cout<<"Send"<<" "<<MessageLen<<" "<<"byte"<<"datas"<<std::endl;;
}

closesocket(ServerSocket);
WSACleanup();
return 0;
}



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/cfanlwn/archive/2009/11/23/4854791.aspx

热点排行